Reputation: 19
I have followed and completed a Unity tutorial however once the tutorial is said and done, there was no function mentioned to restart the game.
Other than closing the application and re-opening, how would I go about adding something like this in?
Upvotes: 1
Views: 22944
Reputation: 267
For example you can reload main scene for restart game.
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
Upvotes: 1
Reputation: 125455
There are do ways to restart game in Unity:
1.Reset every useful variables such as position, rotation, score to their default position. When you use this method, instead of #2, you will reduce how much time it take for your game to load.
Create a UI Button then drag it to the resetButton
slot in the Editor.
//Drag button from the Editor to this
public Button resetButton;
Vector3 defaultBallPos;
Quaternion defaultBallRot;
Vector3 defaultBallScale;
int score = 0;
void Start()
{
//Get the starting/default values
defaultBallPos = transform.position;
defaultBallRot = transform.rotation;
defaultBallScale = transform.localScale;
}
void OnEnable()
{
//Register Button Event
resetButton.onClick.AddListener(() => buttonCallBack());
}
private void buttonCallBack()
{
UnityEngine.Debug.Log("Clicked: " + resetButton.name);
resetGameData();
}
void resetGameData()
{
//Reset the position of the ball and set everything to the starting postion
transform.position = defaultBallPos;
transform.rotation = defaultBallRot;
transform.localScale = defaultBallScale;
//Reset other values below
}
void OnDisable()
{
//Un-Register Button Event
resetButton.onClick.RemoveAllListeners();
}
2.Call SceneManager.LoadScene("sceneName");
to load the scene again. You can call this function when Button.onClick.AddListener
is called..
Create a UI Button then drag it to the resetButton
slot in the Editor.
//Drag button from the Editor to this
public Button resetButton;
void OnEnable()
{
//Register Button Event
resetButton.onClick.AddListener(() => buttonCallBack());
}
private void buttonCallBack()
{
UnityEngine.Debug.Log("Clicked: " + resetButton.name);
//Get current scene name
string scene = SceneManager.GetActiveScene().name;
//Load it
SceneManager.LoadScene(scene, LoadSceneMode.Single);
}
void OnDisable()
{
//Un-Register Button Event
resetButton.onClick.RemoveAllListeners();
}
The decision to which method to use depends on how much Objects in your scene and how much time it takes your scene to load. If the scene has a huge world with baked light maps and HQ textures then go with #1.
Upvotes: 9