Home > OS >  Press "R" to restart (UNITY)
Press "R" to restart (UNITY)

Time:07-21

I need help with my script. Currently, it works fine to restart the level, however if the player holds the "r" key, the game will reload every frame, which causes it to glitch and crash on some systems.

How would I go about altering my script to prevent this issue?

Thank you!

  • David

Here is my current script.

public void Update()
    {   // Reset game on "r" press
         if (!levelIsComplete)
        {
            if (Input.GetKeyDown("r"))
            {
                Time.timeScale = 1f;

                Retry();
            }
    }

public void Retry()
    {
        //Restarts current level
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }


CodePudding user response:

Create a separate script and attach to to a different game object.

Mark it as DontDestroyOnLoad.

public class Reloader : MonoBehaviour {
    void Awake() {
        DontDestroyOnLoad(this.gameObject);
    }

    void Update() {
        if (Input.GetKeyDown(KeyCode.R)) {
            SceneManager.LoadScene(SceneManager.GetActiveScene().name);
        }
    }
}

CodePudding user response:

You should check if the button is pushed if so then dont let it be called again.

public class restartGame: MonoBehaviour {
    bool restart;
    void Awake() {
        DontDestroyOnLoad(this.gameObject);
        restart = false;
    }

    void Update() {
        if (Input.GetKeyDown(KeyCode.R) && !restart) {
            restart = true;  
            SceneManager.LoadScene(SceneManager.GetActiveScene().name);
        }
    }
}

or use Input.GetKeyUp which is called when the button is released

   void Update() {
        if (Input.GetKeyUp(KeyCode.R) && !restart) {
            SceneManager.LoadScene(SceneManager.GetActiveScene().name);
        }
    }
  • Related