How To Pause Without Freezing

Hey, so basically what I want to do is show a particle when the player dies, and then wait five seconds, and then spawn him again. However, using a built-in C# tool like System.Threading.Thread.Sleep(5000); actually stops the frame (i.e sets the framerate to 0 for 5 seconds). How can I wait like this?

Check out coroutines. What you’ll essentially be doing is firing off a “do something in the future” type of thing. In your case you would destroy the player and then say “reload the scene” in five seconds.

In fact, I have a handy class just for this purpose. I’ll post it in the next post after this one, standby.

Here’s a handy “do something later” class.

using UnityEngine;
using System.Collections;

public class CallAfterDelay : MonoBehaviour
{
    float delay;
    System.Action action;

    public static CallAfterDelay Create( float delay, System.Action action)
    {
        CallAfterDelay cad = new GameObject("CallAfterDelay").AddComponent<CallAfterDelay>();
        cad.delay = delay;
        cad.action = action;
        return cad;
    }

    IEnumerator Start()
    {
        yield return new WaitForSeconds( delay);
        action();
        Destroy ( gameObject);
    }
}

You call it like so:

CallAfterDelay.Create( 5.0f,  // this is the time in seconds
() => {

  // here is where you put code you want to happen five seconds from now
  // load a scene?
  // call a respawn function?

});

It has like a million and one uses. It makes a single self-destroying GameObject with all your future goodness on it. If you changes scenes BEFORE it fires, that object is gone, but you can mark the returned object from .Create() as DontDestroyOnLoad() and that will persist.