简体   繁体   中英

How can I delay my script for switching scenes in Unity?

I have a script that I have connected to a button in Unity that switches the scene, but I also have an animation I want to play after the button is pressed. The button starts that animation, but you can't see the animation because the scene switches too quickly.

I've tried using coroutine and timers, but I don't have the technical know how to fully implement them.

I would prefer using a coroutine if that's possible. My code is:

    public void LoadNextScene()
    {
        int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
        SceneManager.LoadScene(currentSceneIndex + 1);
    }

    public void LoadMenuScene()
    {
        SceneManager.LoadScene(0);
    }
}

I want the button to be pressed, then the animation played, and finally the scene switches. Could you please recommend the required code changes to achieve my desire?

There are several different ways to do what you are describing. The three most popular are Co-routines, invoke, and animation events.

The easiest is invoke, here is an example of your code implemented in an invoke. Just call 'CallLoadNextScene'.

public void CallLoadNextScene()
{
    Invoke("LoadNextScene",yourDelay);
}

public void LoadNextScene()
{
    int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
    SceneManager.LoadScene(currentSceneIndex + 1);
}

public void CallLoadMenu(int id)
{
    Invoke("LoadMenuScene",yourDelay);
}

public void LoadMenuScene()
{
    SceneManager.LoadScene(0);
}

Animation events would probably be the most "professional" way to do it because then your have better delegation of responsibilities. Here is a link to Unity's website on those.

A solution using Co-Routines is going to look a lot like the invoke, but since you don't need a lot of advanced functionality Invoke is a little bit faster and easier to use.

Best of luck on your project! :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM