- Home /
How to call OnCollisionEnter2D once when hitting multiple objects?
I have a bullet object that when it collides with an enemy it Instantiates an explosion prefab but when two enemies are on top of each other the method is called twice and spawns two explosions so is there a way to detect multiple enter collisions or call the method once?
Here's the code for the bullet
public GameObject explosion;
private void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.CompareTag("Enemy"))
{
gameObject.SetActive(false);
EXPLOSION();
}
}
Answer by Rechronicle · Oct 19, 2021 at 04:08 PM
I think you can put a bool on the enemy to check if it has already spawned an explosion or not. You can also create auto-reset the bool after a certain amount of time has passed to let another explosion happen.
if (col.explosionAlreadySpawned == false){
SpawnExplosion();
}
Thanks! I made it so every time an explosion is fired it starts a coroutine to reset the bool in a game manager.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How do you make a car drift in unity 2D 1 Answer
Cannot change the value of this integer that I use for array,Cannot change the value of this one. 0 Answers
i have a problem with reloading with Time.time 2d game c# Unity 2020.2 1 Answer