Coroutine not executing yield WaitForSeconds or anything after it

I know this is not exactly a new question, but I’ve been searching the internet all week for an answer. The code works fine, except the yield WaitForSeconds never executes. I’ve posted my code as well as all my Debug.Log checks that appear in the console. For the life of me I cannot figure out why it’s stepping into the coroutine, but not executing the yield.I’ve tried to move things around, but nothing seems to work.

What I’m trying to achieve in this code:

The game object (in this case the stone) is destroyed when the player clicks on it and after a certain amount of time the stone will re-spawn at the same location. This script will need to work for several different game objects.

Try calling the Destroy function after the yield WaitForSeconds.

1 Like

but I want it to wait to re-spawn (instantiate) not destroy?

When you destroy an object, all its coroutines are stopped.
If you want to destroy an object, wait, then res-spawn a new one. You have to write the coroutine doing that into another object, for instance a “CollectibleItemManager”.

1 Like

You can not expect the coroutine to carry on when the object is destroyed!.
I guess you should spawn the new object first, then destroy the old one.
Then put your yield WaitForSeconds into the spawned object. You can get the delay by disabling the object’s renderer (and collider) and reenabling it after yield WaitForSeconds finishes.

1 Like

Just break it down and it looks so obvious.

When the user presses the mouse on this object

  • Log a message
  • Destroy the object that this script is attached to
  • Start a couroutine (Oh wait, we don’t exist anymore, how does that work?, It doesn’t!)

possibly looks like pulling our legs…

You should probably create another script (like SpawnManager.cs or PoolManager.cs) which manages all spawning and destroying the objects, this will also reduce complexity while developing…

1 Like

Thanks everyone, this was a great help. I guess I assumed that the coroutine would still execute since it stepped into it, but not finished it, after the object was destroyed.

[Destroy()](https://docs.unity3d.com/ScriptReference/Object.Destroy.html) is a bit tricky about that. It doesn’t actually fully destroy the object immediately, but marks it as destroyed. As the docs say: “Actual object destruction is always delayed until after the current Update loop, but will always be done before rendering.” It’s also the reason why, when making editor scripts, [DestroyImmediate()](https://docs.unity3d.com/ScriptReference/Object.DestroyImmediate.html) is available as an alternative for cases when it truly is needed.

2 Likes