Change scene twice in a row using Coroutine

Hi there!
In my application I want to change a scene on collision, have the player in that scene for ±20 seconds and then change the scene again.
The problem I am having is that the scene only changes the first time around and does not change to the third scene.

The code I am using is the following:

public float delay = 10;
public float delay2 = 4;
public string NewLevel = "AccidentScene";
public string NewLevel2 = "AfterActionAccident";

void OnCollisionEnter(Collision collision)
{

if (collision.gameObject.tag == "car")
{
UnityEngine.AI.NavMeshAgent agent = Car.GetComponent<UnityEngine.AI.NavMeshAgent>();
agent.isStopped = true;

StartCoroutine(LoadLevelAfterDelay(delay));

IEnumerator LoadLevelAfterDelay(float delay)
{
yield return new WaitForSeconds(delay);
SceneManager.LoadScene(NewLevel);

StartCoroutine(LoadLevelAfterDelay2(delay2));
}

IEnumerator LoadLevelAfterDelay2(float delay2)
{
yield return new WaitForSeconds(delay2);
SceneManager.LoadScene(NewLevel2);

}

}

So the first load level works, but the second one doesn’t, why is this?
I am not very good with coding so I might be missing something basic :slight_smile:

thanks :slight_smile:

Hi @TheOneRaven_1 ,

Does this code persist when the level gets loaded? I bet the object gets destroyed when you load the new scene and that’s why the code doesn’t run.

I’d suggest you make your scene change script as some sort of singleton that can’t be destroyed.

But to just do the initial debugging, add Unity’s default OnDestroy method and do some prints to the log;

void OnDestroy()
{
   Debug.Log("Scene loader script destroyed.");
}

Then you will see when your script is no more. And if it doesn’t get destroyed (if you have parented this script to an object that is marked as DontDestroyOnLoad, do more debug prints to see where it fails.