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)