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?