Help to Load a Random Scene after some time

Hi, I want my start button to display an animation and then load a random scene, but the scene just loads right away and I want it to load after the animation ends
Here’s my code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class LoadRandomScene : MonoBehaviour
{
    public void LoadRandomScenes()
    {
        int index = Random.Range(1, 5);
        SceneManager.LoadScene(index);
        Debug.Log("Scene Loaded");
    }
}

1 Answer

1

There are a few ways to delay an action until later.

  1. Invoke() can call a method after a specific delay. I don’t think you can pass any variables in, so you’d have to set parameters in global variables
    Unity - Scripting API: MonoBehaviour.Invoke
//Call the method MyMethod() after 1s
Invoke(nameof(MyMethod), 1s); 
  1. Co-routines can have yield statements which can stall for a specified amount of time
    Coroutines - Unity Learn
IEnumerator LoadSceneRoutine()
{
    int index = Random.Range(1,5);
    yield return new WaitForSeconds(2f); //based on the length of your animation
    SceneManager.LoadScene(index)
}
public void LoadRandomScenes()
{
    StartCoroutine(LoadSceneRoutine());
}

  1. Animation Event
    The prior two options are fragile because you have to set the delay equal to the length of your animation manually. If you want something tied to the animation itself, then animation events are my preferred option.
    Unity - Manual: Using Animation Events

You can add an event at the end of the animation you want to play and that event can call your LoadRandomScenes() function.