- Home /
How can I restart a single-scene game?
I built 2D board game on unity and I want to make it possible for the player to restart the game at any time (all I need to do is reset all the variables to their initial values and bring the stones to the original position). I don't know why, but Application.LoadLevel() with the same scene as before (I have only this scene) won't work for me. It does bring the stones to the original position, but I get a NullReferenceException whenever I try to play the game after restarting it.
The script I am using is as follows:
using UnityEngine;
using System.Collections;
public class ResetGame : MonoBehaviour
{
void OnEnable()
{
Application.LoadLevel ("Madelinette");
}
}
Any idea about what is causing the problem?
Thanks for any help.
You need to add the level to the build settings (shift + ctrl + b).
Application.LoadLevel (Application.loadedLevel);
Answer by CHPedersen · Sep 19, 2014 at 01:06 PM
You are doing it correctly now. Application.LoadLevel is the way to go, even if you only have the one scene. Your NullReferenceException isn't caused by the approach being wrong, it's caused by some variable state elsewhere which doesn't handle scene transitions well. To fix that, we need more information, preferably the script where the NullReferenceException actually occurs along with the line number that identifies the culprit.
For starters, however, look for things that survive level changes and have the potential to start your game after a call to Application.LoadLevel with a different state than they have when the program starts altogether. These are scripts where you have called DontDestroyOnLoad, and, most likely, static variables.
You got it! Looks like I had referenced some scripts in a class and they were all static variables. I removed that and it all worked properly. Thanks!
Your answer
Follow this Question
Related Questions
Reset The Scene ? 2 Answers
Resetting a Level from within itself 1 Answer
Current Level Load Again After Level Completion 2 Answers
Restart Mecanim's Animator controller 3 Answers
"Reset Level", Application.LoadLevel 1 Answer