I am trying to do when i destroy all boxes something happen.
My code is;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class destroy : MonoBehaviour
{
private string BALL_TAG = "ball";
public AudioClip coin;
public AudioSource src;
public float numBox = 120f;
public bool isDestroyed;
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag(BALL_TAG))
{
src.clip = coin;
src.Play();
Destroy(gameObject);
isDestroyed = true;
}
}
private void Update()
{
boxes();
}
public void boxes()
{
if(isDestroyed == true)
numBox -= 1f;
if(numBox == 119)
SceneManager.LoadScene("mainManu");
}
private IEnumerator Two()
{
yield return new WaitForSeconds(1f);
Destroy(gameObject);
}
}
But it doesn't work.
It is suppose to do when I broke 1 box it sends me to menu.
I think its problem in "numBox -= 1f;" because I don't know hot to make this.
I don't understand your code completely. So, I need to make some assumptions.
I think the Script is attached to the box and every box has this Script. I also think, that your player Shoots Ball. Those Balls have a collider with an ball tag.
There are multiple problems with your code.
The first one is, that your count variable, numBox, is saved in your destroy Script, which is placed on each box.
this means, that every Box is counting for itself.
You have to centralize this. There are multiple ways for doing this.
One way is to declare this variable as static(https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/static)
This is not best practice, but works.
A Better way is to have a Script on Your Player, which holds this number and every Box searches for this Script and change this number if it is destroyed.
The second big Problem is, that your are doing some really weird thing in your Update and the collision handling
First of all, you are setting isDestroyed to true. Then in your boxes method, which is called in every Frame, you are decrementing your numBox variable by one, if this is Destroyed is true.
So if your Box gets hit, you are decrementing every frame.
After that you are checking every frame if your numBox is 119
If so, you change the Scene.
This is the reason, why you are getting to your MainMenu after only one boy
This behaviour is very weird, because it is totally unnecessary. You can reduce your variable directly in in your OnCollisionEnter2D Method.
There are some little things, which can be improved.
When you are trying to play a Sound, you don't have to specify the AudioClip in code. You can assign this directly in Unity on the AudioSource Component via drag and drop. This makes your code simpler.
You are not calling the Two Coroutine. You've specified this Coroutine but don't call it.
//Script on Player
public class PlayerBoxDestroyManager:MonoBehaviour
{
public int StartBoxes = 120;
private int Boxes;
private void Start()
{
Boxes = StartBoxes;
}
public void DestroyBox()
{
//Reduce our Boxes count
//This is equal to Boxes -= 1
// Boxes = Boxes -1
Boxes--;
// If we have less or zero Boxes left, we End call our EndGame methode
if(Boxes <= 0)
{
EndGame();
}
}
private void EndGame()
{
// We change the Scene to the mainMenu
SceneManager.LoadScene("mainManu");
}
}
```
//Script on all Boxes
public class Box : MonoBehaviour
{
public string Balltag = "ball";
//Audio Source the Audio Clip has to be assigned in the Unity editor
public AudioSource Coin;
private void OnCollisionEnter2D(Collision2D collision)
{
//Check it colliding Object has the right Tag
if(collision.transform.tag == Balltag)
{
//Get the reference to the Player Script
PlayerBoxDestroyManager PBDM = FindObjectOfType<PlayerBoxDestroyManager>();
//We can now access the Destroy Box Methode
PBDM.DestroyBox();
//Play the sound
Coin.Play();
//If we destroy our Object now, the Sound would also be deletet.
//We want to hear the sound, so we have to wait, till the sound is finished.
StartCoroutine(WaitTillAudioIsFinished());
}
}
IEnumerator WaitTillAudioIsFinished()
{
//we wait till the sound is finished
while (Coin.isPlaying)
{
yield return null;
}
//if finished, we destroy the Gameobject
Destroy(gameObject);
}
}
I hope I helped you. If you have questions, feel free to ask.
And sorry for my English:)
In my Unity project, I have an if statement set-up where if the conditions are true, my character's box collider will shrink to a specific value when crouching (along with movement speed change, turning speed, etc). And when my character is not crouching anymore, the box collider (along with the other parameters I mentioned) will return to its original size in the else statement.
However, I don't want to keep track of every parameter I change/need to reverse across all my scripts. In the future, my character's base parameters may change, which'll cause me to have to go back and change every else statement I ever make involving changing my character to its default parameters. I can create variables to store my base parameters so I wouldn't have to worry about copy-pasting values if I change them in Unity. But it'll eventually snowball into spaghetti-code territory if I do this method for every parameter I create/change in my scripts.
Is there a simpler way to code in C# where if an If statement is no longer true, it'll reverse all changes it made?
Psuedo code:
float height = 10.42f;
float movementSpeed = 95.89f;
if (condition1==true && condition2==true){
height = 3.5f;
movementSpeed = 40.125f;
}
*code to reverse all changes the If Statement made when it stops being true*
Is there a simpler way to code in C# where if an If statement is no longer true, it'll reverse all changes it made?
No. If you want to revert to an earlier state you need to save that state in advance, e.g. in variables as you propose in the question.
It's look like buff system , it can be todo and undo player status , And it's expandability , So you can design a buffsystem to do it like this:
public interface IBuff
{
void Do(Player player);
void UnDo(Player player);
}
public BuffAddHeight : IBuff
{
public Do(Player player)
{
player.Height += 100;
}
public UnDo(Player player)
{
player.Height -= 100;
}
}
public BuffSeed : IBuff
{
public Do(Player player)
{
player.speed += 100;
}
public UnDo(Player player)
{
player.speed -= 100;
}
}
public class Player
{
// by the way , you can design a buff container to manager your buff.
public void AddBuff(IBuff buff) { buff.Do(this); }
public void RemoveBuff(IBuff buff) { buff.UnDo(this); }
}
I am new to unity and have begun trying to recreate 'flappy bird' from scratch. The pipes when the move out of the game view, speed up then slow down.
Here is the code for the pipes:
public class PipeMoving : MonoBehaviour
{
public float slideSpeed = 5f;
void Update()
{
GetComponent<Rigidbody2D>().AddForce(Vector2.left * slideSpeed, (ForceMode2D)ForceMode.Impulse);
}
}
I guess the reason why your object is slowing down is because you used force mode impulse, which will initially apply that force only once.... In order to fix it do ForceMode2D.Force, which will apply a constant force on that object.
Make the variable private and use SerializeField so it can be visible in the inspector panel and not accessed anywhere else...
[SerializeField]
private float slideSpeed = 5f;
void Awake()
{
myBody = GetComponent<Rigidbody2D>();
}
void Update()
{
move();
}
void move()
{
myBody.AddForce(new Vector2.left(slideSpeed,0), ForceMode2D.Force);
}
Set a variable myBody( or anything you prefer) as the rigidbody component so you can use it multiple times in your code more efficiently...
**Edits listed below:
I have included the keyword 'new' before Vector2.left(slideSpeed,0)
I did that because there is no pre-existing vector which is Vector2.left(slideSpeed,0) so you have to use the keyword new whenever you are declaring a vector for the first time.
If you are considering to reuse the vector, then you can declare it in the top of your code...
leftVector = new Vector2.left(slideSpeed,0);
On doing so, you don't have to use the new keyword when you will use the variable later, incase that confuses you...
As a gamer I'd phrase it like this: An AOE-Stun that stuns everyone it hits and then disappears.
I have enemy objects with a class "EnemyMovement" attached to it.
This class contains a function "Slow". I have a circle that has the class "StunSpell" attached to it. Now I want to call "Slow" once for every enemy object that collides with it.
void OnTriggerStay2D(Collider2D other){
if (other.gameObject.tag == "Enemy") { //Here i want to find every gameobject (by tag "Enemy")
other.GetComponent<EnemyMovement> ().Slow (3, 0f); //Call this function once per gameobject
//And as soon as every object that was found executed "Slow" once:
// -> Destroy(gameObject); to destroy the AOE-Object
}
}
This QA is a bit messy, but it's totally normal and commonplace in video games to simply ...
"...check the distance to each character..."
private void GrenadeTimer()
{
rb.isKinematic = true;
// here is our small explosion...
Gp.explosions.MakeExplosion("explosionA",transform.position);
float radius = splashMeasuredInEnemyHeight *
Gp.markers.GeneralExampleEnemyWidth();
List<Enemy> hits = new List<Enemy>();
foreach(Enemy e in Gp.enemies.all)
{
if (e.gameObject.layer != Grid.layerEnemies) continue;
if ( transform.DistanceTo(e) < radius ) hits.Add(e);
}
hits.SortByDistanceFrom( this.transform );
boss.SequentialHits(hits,damage);
boss.Done(this);
}
It's hard to imagine anything being simpler than that.
Note that we decide on a
radius
in meters, let's say "4.2 meters", inside which we want to do damage to the enemies. (Or, buff them, or whatever the case may be.)
This thing
Gp.enemies.all
is a List<Enemy> ... it holds all the enemies in the game at the moment. Simple right?
If you do not actually have a List<> of all the enemies (or players, NPCs - whatever is relevant) - you are ###ed. Start over on your learning project. Once you have a live List which is unit-tested, come back to this.
This line of code
Grid.layerEnemies
relates to the layer system in Unity. This often causes new hobbyists a problem ...
In reality, you can do absolutely nothing in Unity without using the layers system for every single thing.
It is beyond the scope of this article to get you started on using Layers, so we'll leave that aside. If you prefer, just leave out the line of code in your learning project.
Next. So - we run through and find all the enemies we want to affect. Let us say there are fifteen of them.
Notice that ...
The code gathers them in the loop. They end up in the "hits" list.
By all means, when you're just learning, you can simply apply the buff/damage/etc insinde the loop:
foreach(Enemy e in Gp.enemies.all)
{
if (e.gameObject.layer != Grid.layerEnemies) continue;
if ( transform.DistanceTo(e) < radius )
e.Slow(3f, 0f);
}
However, in any real game, you have to first make a list of the items, and then most typically have a manager (let's say, your "explosions manager!" - whatever) process those hits/ buffs/ damages/ whatever.
The reason is that you can rarely just throw in happenings all in the same frame. Imagine the sound/ visual effects when I quickly explode say fifteen enemies. Almost certainly your creative director / whoever will want them to happen "rat-a-tat-tat" you know? One way or another it will be far more complex than just "triggering them all". (Also, performance-wise you may well have to stagger them - obviously this can be a huge issue involving massive code bases; don't eve mention if the game is networked.) Note that in the actual example given, they end up being staggered, and indeed by distance outwards from the grenade, which looks great.
(As a curiosity, that particular code has been used to explode on the order of one billion grenades!)
Next issue:
looking at your code, you just "GetComponent". The other objects are "dumb". In reality you never do this. Note that in the example code here, there is an actual c# class Enemy
I will paste in some of Enemy at the bottom to give a flavour.
In fact, you almost always keep a List of "the primary c# Class attached to the players/enemies/etc". You generally don't bother much with the GameObject as such.
(If you do need to get to the GameObject, say to Destroy it, you just enemy.gameObject.)
So here, since we're simply checking the distance, you immediately have the Enemy class. (If you're using physics, you have to "GetComponent" to get to the Enemy class; of course you often do that, also.)
That being said - keep in mind the component-behavior nature of Unity:
That being said. My discussion is a bit slippery, there's an "Enemy" class (and indeed there's specific classes for enemies, such as "Dinosaur", "KillerRobot", "AttackParrot" and so on).
Try to bear in mind though, you really need to thing "behaviour-wise" in Unity.
There really shouldn't be an "AttackParrot" class. Really, there should just be components - behaviors - such as
Flies
ThrowsRocks
HasBrightColors
TakesDamage
LaserEyeballs
LandOnTrees
Conceptually an "AttackParrot" would just be a game object, which, happens to have, all of those six behaviors. In contrast, it would not have say "BreathesFire" and "CanHyperjump".
This is all discussed at length here:
https://stackoverflow.com/a/37243035/294884
It's a bit "purist" to say "Oh, there shouldn't be an 'Enemy' class, only behaviors" - but something to bear in mind.
Next up,
You have to have "general" components in a Unity game, which are accessible everywhere. Things like sound effects, scoring and so on.
Unity simply forgot to do this (they'll add it in the future).
Fortunately it's incredibly easy to do. Notice in the above there's a "boss" general component and a "soundEffects" general component which are called to.
In any script in your project that needs to use the general "boss" component or the general "sound" component, it's just...
Boss boss = Object.FindObjectOfType<Boss>();
Sound sound = Object.FindObjectOfType<Sound>();
That's all there is to it...
Boss boss = Object.FindObjectOfType();
This has been explained at vast length so many times, we need only link to it:
https://stackoverflow.com/a/35891919/294884
Note that, if you prefer, the alternate way to do this using PhysX is:
If you'd like to use the built-in physics: Physics2D.CircleCastNonAlloc
If you want, take a couple of days out to master that.
Note that the examples here are for a 2D game, it's identical in 3D.
(When you measure "distance" in 3D, if you game happens only on a flat surface, you may want to bother only measuring the distance on those two axis - but honestly it's irrelevant.)
You may ask, what is SortByDistanceFrom?
SortByDistanceFrom in fact ........ Sorts By Distance From
To save you typing, here is that extension:
public static void SortByDistanceFrom<T>(
this List<T> things, Transform t) where T:Component
{
Vector3 p = t.position;
things.Sort(delegate(T a, T b)
{
return Vector2.Distance(p, a.transform.position)
.CompareTo(Vector2.Distance(p, b.transform.position));
});
}
This raises another issue for new hobbyists.
Example Enemy class
Example - the Enemy class mentioned above ... included to add background.
So, all the actual enemy components (Dinosaurs, Wombats, XFighters, whatever) would derive from this one, overriding (concepts like motion, etc) as appropriate.
using UnityEngine;
using System.Collections;
public class Enemy:BaseFrite
{
public tk2dSpriteAnimator animMain;
public string usualAnimName;
[System.NonSerialized] public Enemies boss;
[Header("For this particular enemy class...")]
public float typeSpeedFactor;
public int typeStrength;
public int value;
// could be changed at any time during existence of an item
[System.NonSerialized] public FourLimits offscreen; // must be set by our boss
[System.NonSerialized] public int hitCount; // that's ATOMIC through all integers
[System.NonSerialized] public int strength; // just as atomic!
[System.NonSerialized] public float beginsOnRight;
private bool inPlay; // ie, not still in runup
void Awake()
{
boss = Gp.enemies;
}
void Start()
{
}
public void ChangeClipTo(string clipName)
{
if (animMain == null)
{
return;
}
animMain.StopAndResetFrame();
animMain.Play(clipName);
}
public virtual void ResetAndBegin() // call from the boss, to kick-off sprite
{
hitCount = 0;
strength = typeStrength;
beginsOnRight = Gp.markers.HitsBeginOnRight();
Prepare();
Gp.run.runLevel.EnemyAvailable();
}
protected virtual void Prepare() // write it for this type of sprite
{
ChangeClipTo(bn);
// so, for the most basic enemy, you just do that
// for other enemy, that will be custom (example, swap damage sprites, etc)
}
void OnTriggerEnter2D(Collider2D c)
{
GameObject cgo = c.gameObject;
// huge amount of code like this .......
if (cgo.layer == Grid.layerPeeps) // we ran in to a "Peep"
{
Projectile p = c.GetComponent<Projectile>();
if (p == null)
{
Debug.Log("WOE!!! " +cgo.name);
return;
}
int damageNow = p.damage;
Hit(damageNow);
return;
}
}
public void _stepHit()
{
if ( transform.position.x > beginsOnRight ) return;
++hitCount;
--strength;
ChangeAnimationsBasedOnHitCountIncrease();
// derived classes write that one.
// todo, actually should the next passage only be after all the steps?
// is after all value is deducted? (just as with the _bashSound)...
if (strength==0) // enemy done for!
{
Gp.coins.CreateCoinBunch(value, transform.position);
FinalEffect();
if ( Gp.skillsTest.on )
{
Gp.skillsTest.EnemyGottedInSkillsTest(gameObject);
boss.Done(this);
return;
}
Grid.pops.GotEnemy(Gp.run.RunDistance); // basically re meters/achvmts
EnemyDestroyedTypeSpecificStatsEtc(); // basically re achvments
Gp.run.runLevel.EnemyGotted(); // basically run/level stats
boss.Done(this); // basically removes it
}
}
protected virtual void EnemyDestroyedTypeSpecificStatsEtc()
{
// you would use this in derives, to mark/etc class specifics
// most typically to alert achievements system if the enemy type needs to.
}
private void _bashSound()
{
if (Gp.bil.ExplodishWeapon)
Grid.sfx.Play("Hit_Enemy_Explosive_A", "Hit_Enemy_Explosive_B");
else
Grid.sfx.Play("Hit_Enemy_Non_Explosive_A", "Hit_Enemy_Non_Explosive_B");
}
public void Hit(int n) // note that hitCount is atomic - hence strength, too
{
for (int i=1; i<=n; ++i) _stepHit();
if (strength > 0) // bil hit the enemy, but enemy is still going.
_bashSound();
}
protected virtual void ChangeAnimationsBasedOnHitCountIncrease()
{
// you may prefer to look at either "strength" or "hitCount"
}
protected virtual void FinalEffect()
{
// so, for most derived it is this standard explosion...
Gp.explosions.MakeExplosion("explosionC", transform.position);
}
public void Update()
{
if (!holdMovement) Movement();
// note don't forget Translate is in Space.Self,
// so you are already heading transform.right - cool.
if (offscreen.Outside(transform))
{
if (inPlay)
{
boss.Done(this);
return;
}
}
else
{
inPlay = true;
}
}
protected virtual void Movement() // override for parabolas, etc etc
{
transform.Translate( -Time.deltaTime * mpsNow * typeSpeedFactor, 0f, 0f, Space.Self );
}
}
So that's a general enemy class. Then you have derives of that, such as Ufo, Dinosaur, Tank, XWingFighter, etc etc. Here's Ufo ...
Note that it overrides many things. It seems to override "Prepare" (the comments suggest it "starts higher", and you can see it overrides other things.
using UnityEngine;
using System.Collections;
public class Ufo:Enemy
{
public Transform projectilePosition;
protected override void Prepare()
{
// ufo always start up high (and then zip up and down)
transform.ForceY(Gp.markers.StartHeightHighArea());
animMain.StopAndResetFrame();
animMain.Play(bn + "A");
animMain.StopAndResetFrame();
Invoke("ZipDown", Random.Range(0.6f,0.8f));
}
protected override void OnGamePause()
{
CancelInvoke();
StopAllCoroutines();
}
protected override void OnGameUnpause()
{
Attack();
if(transform.position.y<0f)
ZipUp();
else
ZipDown();
}
private float fZip = 3.3f;
private void ZipDown() { StartCoroutine(_zipdown()); }
private void ZipUp() { StartCoroutine(_zipup()); }
private IEnumerator _zipdown()
{
Grid.sfx.Play("Enemy_UFO_Move_Down");
float tLow = Gp.markers.StartHeightLowArea();
while (transform.position.y > tLow)
{
transform.Translate(0f,
fZip * -Time.deltaTime * mpsNow, 0f,Space.Self );
yield return null;
}
Attack();
Invoke("ZipUp", Random.Range(0.7f,1.4f));
}
private IEnumerator _zipup()
{
Grid.sfx.Play("Enemy_UFO_Move_Up");
float tHigh = Gp.markers.StartHeightHighArea();
while (transform.position.y < tHigh)
{
transform.Translate(0f,
fZip * Time.deltaTime * mpsNow, 0f,Space.Self );
yield return null;
}
Attack();
Invoke("ZipDown", Random.Range(0.7f,1.4f));
}
private void Attack()
{
Grid.sfx.Play("Enemy_UFO_Shoot");
animMain.Play();
Invoke("_syncShoot", .1f);
}
private void _syncShoot()
{
Gp.eeps.MakeEepUfo(projectilePosition.position);
}
protected override void ChangeAnimationsBasedOnHitCountIncrease()
{
// ufo just goes 4,2,out
if (strength == 2)
{
// if any attack, cancel it
CancelInvoke("ShootGreenPea");
CancelInvoke("Attack");
// on the ufo, anim only plays with attack
animMain.StopAndResetFrame();
animMain.Play(bn + "B");
animMain.StopAndResetFrame();
Invoke("Attack", 1.5f.Jiggle());
}
}
protected override void EnemyDestroyedTypeSpecificStatsEtc()
{
Grid.pops.AddToEnemyCount("ufo");
}
}
Let's think about the idea of "overrides in the Enemy class".
Overrides in an example Enemy class......
The many enemies have different types of movement, right? The general paradigm in the game is things moving in 2D, kinematically (ie, we "move them a certain amount of distance each frame" - not using PhysX here). So the different enemies move in radically different ways.
Here's one that moves in a certain way ... (the comments explain it)
protected override void Movement()
{
// it enters at about 2x normal speed
// the slow crossing of the stage is then about 1/2 normal speed
float mpsUse = transform.position.x < changeoverX ? mpsNow*.5f : mpsNow * 2.5f;
transform.Translate( -Time.deltaTime * mpsUse * typeSpeedFactor, 0f, 0f, Space.Self );
// recall that mpsNow was set by enemies when this was created, indeed
// nu.mpsNow = ordinaryMps * widthSpeedFactor;
}
Here's one that goes along, but sometimes "drifts downwards..."
protected override void Movement()
{
float mm = mpsNow * typeSpeedFactor;
if ( fallingMotion )
transform.Translate(
-Time.deltaTime * mm,
-Time.deltaTime * mm * fallingness, 0f,
Space.Self );
else
transform.Translate(
-Time.deltaTime * mm, 0f, 0f,
Space.Self );
}
Here's one that seems to follow a sinus ...
protected override void Movement()
{
transform.Translate( -Time.deltaTime * mpsNow * typeSpeedFactor, 0f, 0f, Space.Self );
float y = Mathf.Sin( basis-transform.position.x * (2f/length) );
y *= height;
transform.transform.ForceY( y );
}
Here's one that does complex speed changes, zooming around
protected override void Movement()
{
// it enters at about 2x normal speed
// it appears to then slow crossing of the stage about 1/2 normal speed
// however it then zooms to about 3x normal speed
float mpsUse = mpsNow;
float angled = 0f;
if ( transform.position.x > changeoverX) //enter quickly
mpsUse = mpsNow * 3f;
if ( transform.position.x < thenAngled) // for bead, angled section
{
mpsUse = mpsNow * 1.5f;
angled = leanVariation;
}
transform.Translate(
-Time.deltaTime * mpsUse * typeSpeedFactor,
-Time.deltaTime * mpsUse * typeSpeedFactor * angled,
0f, Space.Self );
}
You could make the movement anything - flying, running, bouncing, whatever.
It's all handled in c# by the protected override concept.
Static "globals" class ... simpler than a general component, for simply "holding" certain variables
Here's a trivial example of a static class which holds what you might as well call "globals", In a game engineering milieu, it's sensible to have certain things as "globals".
using UnityEngine;
using Shex;
using System.Collections;
using System.Collections.Generic;
static class Gp
{
public static Enemies enemies;
public static Pickups pickups;
public static Coins coins;
public static Peeps peeps;
public static Eeps eeps;
}
So TBC complicated "general" systems like SoundEffects, Boss, Scoring, AI, Networking, Social, InAppPurchase etc etc as described above, would indeed by the "preload" type objects as explained. (ie, you're using Boss boss = Object.FindObjectOfType(); at the top of any script, in any scene etc, that needs them.)
But for simply variables, things, that just need to access everywhere, you can use a trivial static class like that. Often just the one static class (called something like "Gameplay" or "Gp") does the job for the whole project.
{By all means, some teams would say "screw that, don't use a static class, put it in a "general" ("preload-style") component like Boss...."}
Note that of course a static class is NOT a real MonoBehavior - you "can NOT actually "DO" anything inside it in Unity". It's only for "holding variables" (most often, Lists) you want to access easily everywhere.
Again, be sure to remember that a static class is quite simply NOT a Unity game object or component - hence it very literally is not part of your game; you literally can not "do" anything whatsoever in a static class. To "do" anything, at all, in Unity it must be an actual Component, literally on a specific GameObject, at some position.
Thus for example it's completely useless trying to keep your "score" in a simple static class. Inevitably in relation to the "score" you will want to do all sorts of things (change the display on screen, award points, save encrypted preferences, trigger levels ... whatever, there is a lot of stuff to do). You absolutely cannot do that in a static - you can not "do" anything, at all, in a static - it must be an actual Unity game object. (ie, using the "preload system".) Once again statics are just for literally keeping track of some basically "global" variables, usually lists of things. (Things like "screen markers" are the perfect example.)
Just BTW in game development an "eep" is an enemy projectile and a "peep" is a player projectile, heh!
(Posted on behalf of the OP).
I solved it using a List to check which enemies are colliding with the Circle:
void CallStun(Collider2D coll){
if (coll.gameObject.tag == "Enemy") {
coll.GetComponent<EnemyHealth> ().TakeDamage (damage);
coll.GetComponent<EnemyMovement> ().Slow (3, 0f);
}
}
void OnTriggerStay2D(Collider2D other){
if (stun == false) {
return;
}
if (!collList.Contains (other)) { //if the object is not already in the list
collList.Add (other); //add the object to the list
CallStun (other); //call the functions on the specific object
} else {
Destroy (gameObject); //if no(more) collisions occur -> destroy the circle object
}
}
In the EnemyMovement class have an OnTriggerEnter method. Tag the spell and put a 2dCollider on it. When the OntriggerEnter is hit with tag == "slow spell" call the slow.
Basically I would do it the reverse way you are currently doing it. Doing it the other way will easily alow you to interact with anything that hits the enemy (since that's the intended behavior)
I tried to make a script that moves an object back and forth between two points. But it just flies in the ifinity. I tried to find the problem whole evening but idk.
here is the code:
using UnityEngine;
public class MovementBetweenPoints : MonoBehaviour {
public Transform[] keyPoints;
public float speed;
private int currentKeyPoint;
// Use this for initialization
void Start ()
{
transform.position = keyPoints[0].position;
currentKeyPoint = 1;
}
// Update is called once per frame
void Update ()
{
if (transform.position == keyPoints[currentKeyPoint].position)
{
currentKeyPoint++;
}
if (currentKeyPoint >= keyPoints.Length)
{
currentKeyPoint = 0;
}
transform.position = Vector3.MoveTowards(transform.position, keyPoints[currentKeyPoint].position, speed * Time.deltaTime);
}
}
Your script works fine as it is. you need to make sure that speed is set to a value greater than 0 in the inspector, and that the keypoints array contains some gameobjects in the inspector too, and you are good to go
I'm sure the problem comes with this part of the code where you check if the position of the object is equal at some waypoint. Instead of:
if (transform.position == keyPoints[currentKeyPoint].position)
{
currentKeyPoint++;
}
try to do something less agressive, and give a bit of margin like:
if (Vector3.Distance(transform.position - keyPoints[currentKeyPoint].position) <= min_Distance)
{
currentKeyPoint++;
}
because it's almost impossible that two objects with different speeds match at the same point. Instead of this, you'll use min_Distance to check it.