I'm developing an university exercise in Unity2D where I need to restart my game by pressing the key R. The game is a ball that moves when you press space. I added some code but when I press R it won't happen anything.
My code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class RestartGame : MonoBehaviour
{
public void restart()
{
if (Input.GetKeyDown(KeyCode.R))
{
SceneManager.LoadSceneAsync(
SceneManager.GetActiveScene().buildIndex);
}
}
}
I saw in a forum that I had to create an empty object and add the script there to make it work. But for some reason it won't happen anything.
Help is much appreciated.
If you want to check for User Input
you need to do that in the Update()
Method that is provided by Unity.
Example:
private void Update() {
if (Input.GetKeyDown(KeyCode.R)) {
SceneManager.LoadSceneAsync(
SceneManager.GetActiveScene().buildIndex);
}
}
If you don't use the Update Method or a Method that is called each frame (eg. OnTriggerStay()
) you won't be able to detect if a User actually pressed a Key.