0

I am using unity with C# and want to let the player keep moving for a bit after losing, and only then reload the scene. I tried:

{
    if (inf.collider.tag == "Obstacle") {
        movement.enabled = false;
        Camera.enabled = false;
        System.Threading.Thread.Sleep(1000);
        SceneManager.LoadScene("Level");
    }
}

But the problem is that the entire game and physics freeses when it gets to the sleep line. How would I wait to execute SceneManager.LoadScene("Level") without freezing all proccesses?

Itay123
  • 61
  • 1
  • 6
  • You could schedule a scene reload event and meanwhile block input. – Lcj Apr 12 '21 at 18:44
  • @MD.RAKIBHASAN - No. `Thread.Sleep` is almost always the wrong tool to use when you want to wait for something. See https://stackoverflow.com/questions/8815895/why-is-thread-sleep-so-harmful – Broots Waymb Apr 12 '21 at 18:48

2 Answers2

0

You should try using a coroutine https://docs.unity3d.com/ScriptReference/MonoBehaviour.StartCoroutine.html

using System.Collections;
//....
{
  if (inf.collider.tag == "Obstacle") 
  {
    movement.enabled = false;
    Camera.enabled = false;
    StartCoroutine(LoadSceneAfterTime(1));
  }
//....
}
private IEnumerator LoadSceneAfterTime(float waitTime)
{
       yield return new WaitForSeconds(waitTime);
       SceneManager.LoadScene("Level");
}
gluedpixel
  • 292
  • 3
  • 6
0

Try to use Invoke() method.

{
    if (inf.collider.tag == "Obstacle") {
        movement.enabled = false;
        Camera.enabled = false;
        Invoke("LoadScene", 1.0f);
        
    }
}

public void LoadScene()
{
   SceneManager.LoadScene("Level");
}
Art Zolina III
  • 497
  • 4
  • 10
  • hi, I would like to try and use your suggestion but am not sure how make it so I can use that line (the using X lines at the start of the code). a reply would be much appreciated – Itay123 Apr 13 '21 at 18:00