简体   繁体   中英

Determine action according to previous scene in unity

I have the following script:

void Update() 
{
    //timed
    sc = PlayerPrefs.GetInt("timedScore");
    score.text = sc.ToString();
    //arcade
    sc = PlayerPrefs.GetInt("arcadeScore");
    score.text = sc.ToString();
}

And I want to execute the timed statement if my previous scene was 1 and arcade if my previous scene was 2.

I tried using the SceneManager , but it seems that it doesn't have a function for determining previous scene. Or is there some other way, since my game has timed and arcade mode so I want to load the score of the correct previous scene.

The SceneManager.GetActiveScene() function is very useful for this. It is used to get information about the current scene.

Before you load another scene, you have to get the current scene then save its name.

string currentScene = SceneManager.GetActiveScene().name;
PlayerPrefs.SetString("LastScene", currentScene);
PlayerPrefs.Save();

Now, you can freely load another scene.


To check the last scene from the newly loaded scene, read the "LastScene" key.

//Read Last scene
string lastScene = PlayerPrefs.GetString("LastScene", null);
if (lastScene != null)
{
    if (lastScene == "blahblahblah")
    {
        //Do something
    }

    if (lastScene == "Otherblahblahblah")
    {
        //Do something
    }
}

This could have been easily done with SceneManager.GetActiveScene().buildIndex but I didn't use this because SceneManager.GetActiveScene().buildIndex returns -1 if the the scene is loaded from AssetBundle.

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