I’m building a 2D platformer in C#. When my player dies, I start a coroutine that:
add particles
start a sound affect
wait for 1 second
load the next level
While this happen I would like to destroy the player (to make it invisible and to prevent the user from moving it). However, if I do Destroy(gameObject) at the begining of my coroutine, thing stop to work. And that’s normal: I’m destroying the object where the coroutine is.
So how can I destroy my player (make it invisible, and immovable) without using the “Destroy” function? Thanks!
For the objects: Call the SetActive() method on each with false after destruction. Add a flag (“bool isAlive”) somewhere readable by the coroutine/input scripts. I’m not entirely sure all that you do even needs a coroutine, actually. If the first thing you do is set isAlive false and disable/hide the respective objects, that should be fine.
I think you’re looking for a code solution where what you really need is an architectural solution. Take a step back.
By making this rigid relationship between your player and explosion objects (and polluting your player code with explosion code) you’re making something that is going to be extremely difficult to work with in the future.
Consider writing a separate explosion script. It will make your life a lot easier:
You can update the player without worrying about breaking the explosion.
You can update the explosion without worrying about breaking the player.
You can use the explosion for other things in your game as well.
You can have players that don’t explode (if you so desire).
Once you have made your explosion prefab you can simply instantiate it wherever you need it.