After closing the game and reopening it, I want to load the last scene, so the player can continue from the level he reached. I've tried using PlayerPrefs as you see in the code bellow, but the game crash on startup.
GameManager Script:
bool GameHasEnded = false;
public float RestartDelay = 2f;
public float NextLevelDelay = 5f;
int level_index;
private void Start()
{
level_index = PlayerPrefs.GetInt("Last_Level");
SceneManager.LoadScene(level_index);
}
public void CompleteLevel()
{
Invoke("NextLevel", NextLevelDelay);
level_index = level_index++;
PlayerPrefs.SetInt("Last_Level", level_index);
}
public void EndGame()
{
if (GameHasEnded == false)
{
GameHasEnded = true;
Invoke("Restart", RestartDelay);
}
}
void NextLevel()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex +1);
}
void Restart()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().path);
}
}
All scenes are linked with GameManager
, they all have the same code that load the next scene:
FindObjectOfType<GameManager>().CompleteLevel();