how to write script to restart game after game over
hi, i am using this code to restart game but i dont know how do i add? i just want if i push space button then the game is restart to from beginning of mainScene.
void Update()
{
if (GameStateManager.GameState == GameState.Dead)
{
if (WasTouchedOrClicked())
{
restart game
}
}
}
bool WasTouchedOrClicked()
{
if (Input.GetKey(KeyCode.Space))
return true;
else
return false;
}
Answer by Landern · Aug 25, 2016 at 02:47 PM
Add to the top of your class:
using UnityEngine.SceneManagement;
Update your update method to reload the current scene either by name or index.
void Update()
{
if (GameStateManager.GameState == GameState.Dead)
{
if (WasTouchedOrClicked())
{
// Get active scene name and reload that scene based off name, could also buildIndex instead of name.
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
}
If you're not looking to reload but want it in a "new game" state, you will need to code out all the reset methods for your game and gameobject locations.
actually i already did it before like you said, but still wont restart. i only have 1 active scene that is mainScene with 0 index number. do i need to write down the name of the scene or index number? if yes where should i write down? i already tried any option but still wont restart.
If you have time, can you write for me example for "reset" the game means please? I lack of example and unity tutorial doesnt has a simple answer for my question. I am curious, how do i restart a game like i run the game for the first start?