edilla
1
I have a problem with the death of my enemies. when ever I kill an enemy I would like a kill count to go up by one point, but since I have a IEnumerator of 5 seconds before the gameobject is destoryed, the kill count goes up until the gameobject is destroyed. here’s my code it’s in C#
IEnumerator enemyDead(){
yield return new WaitForSeconds (5);
Destroy (gameObject);
}
private bool alive(){
bool alive = false;
if (health > 0) {
moveSpeed = 3;
rotationSpeed = 5;
alive = true;
animation.CrossFade (runClip.name);
Attack ();
}
return alive;
}
private bool dead(){
bool dead = false;
if (health <= 0) {
moveSpeed = 0;
rotationSpeed = 0;
animation.CrossFade (dieClip.name);
dead = true;
StartCoroutine ("enemyDead");
collider.enabled = false;
scoreManager.kills += 1;
scoreManager.killsCoins += 1;
}
return dead;
}
}
here’s my scoreManager
public static int score;
public static int kills;
public static int killsCoins;
GUIText text;
public int currScore;
public Font font;
public Color color;
public int winScreenWidth, winScreenHeight;
private bool showWinScreen;
public bool paused;
void Awake (){
//score = 0;
if (PlayerPrefs.HasKey ("kills")) {
kills = PlayerPrefs.GetInt("kills");
}
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (kills >= 20) {
PlayerPrefs.SetInt ("kills", kills);
showWinScreen = true;
paused = true;
}
}
Move your ‘dead’ and ‘alive’ variables outside of the functions, and don’t set them to false at the start of each.
Beyond that, perhaps you can collapse them into one. If the enemy is either alive or dead, you really only need to keep track if he is alive OR dead, not both (since alive is just not dead, and dead is just not alive).
Then, in your dead() method, just check to see
if(health <= && !dead)
After that, let’s assume you keep the dead variable instead of the alive one, set dead to false in the alive method.