Alternatively, and I think ideally, you should avoid having to “Find” GameObjects in a scene hierarchy. Instead, for any such purpose, you should hold references of such spawn-able entities somewhere in your code separately.
A way to go about your situation could be that
You declare a static System.Action in your Enemy component attached to each enemy gameobject
Send out an enemy’s own reference to the action in Start() method of your Enemy class
Have A class, say GameLogic, contain the action definition for your enemies. So in this class, you could keep a list of all enemies
On collision with an enemy, tell the GameLogic to destroy gameobjects associated with all enemies.
FindObjectsWithTag() is very fast though (much faster than regular GameObject.Find()), and he only has to call it once; it’s not like it’s done every frame. The extra bookkeeping required to manually keep a reference to all enemies will not pay off, and it only serves to make the code more complex.
I wouldn’t be surprised if the tag system basically is doing what you are suggesting, but built-in.
Thank you for your help
I have only two more questions about my problem.
The code worked, but not all the objects were destroyed.
For example:
I have a hazard of 10 enemies moving towards the player.
Five enemies is visible in the scene when my player collide with one of them and all 5 destroys thanks to the new code, but the five that hasn’t yet arrived into the scene aren’t destroyed. I hope you understand what I mean
Second question,
Is it possible to make all of the enemies explode with Instantiate like the player and the enemy that collided?
FindObjectsWithTag() is way faster than GameObject.Find(), agreed! It also keeps a list of all gameobjects with a specific tag. But generally, simple arrays are the fastest, followed by Lists and then FindObjectsWithTag().
@off112 … If the other 5 enemies spawn after the collision, they would obviously not get destroyed. The logic that destroyed them is already in the past. I hope you understand what I mean
I’ll hope I can explain my second question better. If you look at my code above, that I trigger an explosion with Instantiate when the player collide with an enemy. But it’s only the enemy that collides that will explode. I would like that all the enemies explodes.