- Home /
Double subtraction issue
Hi guys,
I'm experiencing something weird. This simple if statement gives me a non-correct output.
if(lifeTime < 0f)
{
GameObject.FindWithTag("GameController").GetComponent<EnemySpawnScript>().enemyOnScreen -= 1;
Destroy(gameObject);
}
The subtraction on the variable enemyOnScreen is done two times instead of one. How's this possible if the object is immediately destroyed after the subtraction?
Answer by maccabbe · Feb 25, 2015 at 09:39 PM
This is probably because actual destruction is delayed until the end of the Update loop (after all objects are updated).
But i just checked that the additional subtraction is done almost at the beginning of Update loop when lifeTime is still not below zero. How's that possible? I already tried to remove the subtraction line of code and as expected nothing happens. So the problem is that for some reason that line is executed one time even when the if condition is not reached.
Just add some other check.
bool oneShot = false;
if(lifeTime < 0f)
{
if(!oneShot)
{
oneShot = true;
GameObject.FindWithTag("GameController").GetComponent<EnemySpawnScript>().enemyOnScreen -= 1;
Destroy(gameObject);
}
}
Already tried that kind of check. It doesn't work unfortunately.
I checked the entire solution and there is no other place where that variable is subtracted. What else could it be?