- Home /
How is it possible to destroy a GameObject twice?
I'm making a 2D game. Enemies drop "power" when they die. It took me a long time to figure out why enemies sometimes drop two "powers" instead of one. It's because I have an error in my collision logic, so sometimes my enemies get hit twice by one bullet.
When enemies get hit, they spawn a "power" object and then destroy their own gameObject. However, a second hit is still allowed to execute code, as well as destroy the gameObject again.
float powerValue = 1;
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.layer == LayerMask.NameToLayer("PlayerBullets"))
{
health -= collision.gameObject.GetComponent<BulletBasicCollision>().damage;
}
if (health <= 0)
Die();
}
private void Die()
{
GameObject power = Instantiate(powerPrefab, transform.position, transform.rotation) as GameObject;
power.GetComponent<Power>().SetValue(powerValue);
Destroy(gameObject);
}
By using break points and having the condition that it only triggers after 2 hits, I can see that the OnTriggerEnter2D function sometimes triggers twice, and the code executes all the way through the Die function. Which includes spawning two "power" objects and running the Destroy(gameObject) line twice. How is that possible?
Answer by Daemonhahn · Jul 25, 2017 at 06:19 PM
This is an error that has happened before and unfortunately the only way to control it is to use a bool to determine if the collision has happened and then ignore subsequent collisions.
something like:
collided = false;
OnTriggerEnter() { if(collided) return;
else collided = false
}
around your code
I see. Thanks for your answer. Yes I ended up using a bool to prevent this.
Just to clarify, do you mean "else collided = true" ?