Comparing scene names to load the correct scene?

I need help… I’m trying to save the scene the player is in with PlayerPrefs so he doesn’t have to start playing from the beginning again everytime he restarts the game. So I made 2 scripts. One fpr the main menu and one to save the level the player is in.
This is the script for saving:

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

public class LevelSaveLoad : MonoBehaviour
{
    public Scene m_Scene;
    public string SceneName;
    public string level;
    public void Start()
    {
        level = PlayerPrefs.GetString("level", SceneName);
    }

    public void Update()
    {
        m_Scene = SceneManager.GetActiveScene();
        SceneName = m_Scene.name;
        PlayerPrefs.SetString("Level", SceneName);
    }
}

And for the main menu:

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

public class MainMenu : MonoBehaviour {

    LevelSaveLoad LoadingSystem;

    void Start()
    {

    }

    public void PlayGame ()
    {
        if(LoadingSystem.SceneName == PlayerPrefs.GetString("level"))
        {
            SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
        }
        else SceneManager.LoadScene(PlayerPrefs.GetString("level"));
    }

    public void QuitGame()
    {
        Debug.Log("QUIT!");
        Application.Quit();
    }
   
}

I know at this point the saving is not very usefull because it is called in update but i’m gonna solve that later.
It should work so that I press a play button and it either load the saved level, or if the saved level is the main menu, it should just load the next scene from build index. But I always get the error
NullReferenceException: Object reference not set to an instance of an object
MainMenu.PlayGame () (at Assets/Scripts/MainMenu.cs:17)

Try in LevelSaveLoad

public static string SceneName;

Because that LoadingSystem seems to be null

Not sure tho what exactly is null.

1 Like

Now I’m getting the error
Assets\Scripts\MainMenu.cs(17,12): error CS0176: Member ‘LevelSaveLoad.SceneName’ cannot be accessed with an instance reference; qualify it with a type name instead

I dont really understand that, do you know what I have to change?
I’m unexperienced in unity

I think that is because you also have to change in mainMenu

LoadingSystem.SceneName

Change in to:

LevelSaveLoad.SceneName
1 Like

hmmm now it tries to compare an empty stringg but I dont know which string is empty and why

There’s only 1 string cuz it’s static.

LevelSaveLoad SceneName

Has to be set to some thing it only 1 exists

1 Like

I found the problem. In the first script I set the scene to the PlayerPref “Level” but used “level” everywhere else xD