Hey so I get a problem where sometimes when I kill an enemy it decreases the value by 2 rather than 1. It seems to happen with every second or so enemy I kill and I can’t figure it out. Any help is greatly appreciated, thanks~!
My ManagerScript has public int EnemyInstances = 10 When all are spawned and is meant to decrease by 1 when an Enemy dies.
_
On my Enemy Script:
public class Target : MonoBehaviour {
public float health = 50f;
public void TakeDamage (float amount)
{
health -= amount;
if (health <= 0f)
{
GameManager.instance.EnemyInstances -= 1;
Die();
}
}
void Die ()
{
Destroy(gameObject);
}
}
public class Target : MonoBehaviour
{
public float health = 50f;
public bool Alive = true;
public void TakeDamage (float amount)
{
health -= amount;
if (health <= 0f)
{
if (Alive)
{
Alive = false;
GameManager.instance.EnemyInstances -= 1;
Die();
}
}
}
void Die ()
{
Destroy(gameObject);
}
}
For such book keeping you may want to use OnDestroy or OnDisable instead. Generally OnDestroy would be the best candidate however if you want to use object pooling this would be a problem as the object isn’t destroyed when you use an object pool. In this case OnDisable would be better.