I have 2 game objects: Explosion
and Enemy
. At any given point, an enemy can collide with multiple Explosion
game objects at the same exact time. This causes a few issues when I'm trying to destroy the Enemy
game object.
This is the function that destroys the game object:
bool isDead = false;
public void KillCharacter () {
if (!isDead) {
isDead = true;
Debug.Log ("kill enemy...");
}
}
If I use OnTriggerEnter2D
inside the Enemy
script, like so:
void OnTriggerEnter2D (Collider2D other) {
if (other.gameObject.tag == "Explosion") {
KillCharacter();
}
}
In case two explosions spawn on the position of the enemy, Debug.Log
inside the KillCharacter
function will fire twice, even though I set the isDead
bool to true on the first run.
The only solution I found was to call KillCharacter
from the Explosion
script, like so:
void OnTriggerEnter2D (Collider2D other) {
if (other.gameObject.tag == "Enemy") {
other.gameObject.GetComponent<Enemy> ().KillCharacter ();
}
}
Is there a way to run the OnTriggerEnter2D
from the Enemy
script, as I originally intended? Or is having the KillCharacter
handle all the death logic and calling it from outside good enough?
isDead
to true the first time, so even if two collisions are happening at a nearly identical time, they must still be handled sequentially in some way, and the very first one closes the processing for the second. Could you check your code some more to see if either theisDead
is perhaps set to false somewhere again -- or that maybe your script is attached to two different gameObjects, and you are mistaking the "kill enemy" debug log for a single gameObject? E.g. give all objects a different name and useprint("killed " + name)
. \$\endgroup\$