Reputation: 11
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!
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);
}
Upvotes: 1
Views: 12822
Reputation: 59
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SceneController : MonoBehaviour
{
private bool canRestart = false;
private void Update()
{
if (Input.GetKeyDown(KeyCode.R) && canRestart)
{
canRestart = false;
Restart();
}
}
private void Restart()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
Upvotes: 0
Reputation: 3059
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);
}
}
Upvotes: 1
Reputation: 4888
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);
}
}
}
Upvotes: 2