How to Restart at the Current Scene in Unity

 


If the player died and you need to restart the game at the same level that the player died in. You should to use PlayerPrefs to store level name that the player last died in. In your player script, when the player dies
use this code 


 // Save the current level name to PlayerPrefs
        string currentLevelName = SceneManager.GetActiveScene().name;
        PlayerPrefs.SetString("LastLevel", currentLevelName);
        PlayerPrefs.Save();

clearfication of this code:


1- SceneManager.GetActiveScene().name: Retrieves the name of the currently active scene in Unity.


2- PlayerPrefs.SetString("LastLevel", currentLevelName): Stores the retrieved scene name in PlayerPrefs using the key "LastLevel". 


3- PlayerPrefs.Save(): Saves the PlayerPrefs data to disk.


this code captures the name of the current level and saves it so that the game remembers which level the player was on when they die. 


and use this code in the restart method


 public void Restart()
    {
        // Get the last played level name from PlayerPrefs
        string lastLevelName = PlayerPrefs.GetString("LastLevel");

        // Check if the retrieved level name is not empty (meaning it was previously set)
        if (!string.IsNullOrEmpty(lastLevelName))
        {
            // Load the last played level
            SceneManager.LoadScene(lastLevelName);
        }
        else
        {
            // If no last level name is found (e.g., first play), load a default level (e.g., "Level 1")
            SceneManager.LoadScene("Level 1");
        }
    
    }

In this method, retrieve the last played level name from PlayerPrefs. If it exists, load that level. Otherwise, load a default level.


and that's it ! the problem is solved!


Happy coding


Previous Post Next Post

Contact Form