在 Unity 中用一个键重启场景

Restarting the scene with a key in Unity

我正在 Unity2D 中开发一个大学练习,我需要按 R 键重新启动我的游戏。游戏是一个球,当你按下 space 时它会移动。我添加了一些代码,但是当我按 R 时,它不会发生任何事情。

我的代码:

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);
        }
    }
}

我在一个论坛上看到我必须创建一个空对象并在其中添加脚本才能使其工作。但由于某种原因,它不会发生任何事情。

非常感谢您的帮助。

如果要检查 User Input you need to do that in the Update() Unity 提供的方法。

示例:

private void Update() {
    if (Input.GetKeyDown(KeyCode.R)) {
        SceneManager.LoadSceneAsync(
            SceneManager.GetActiveScene().buildIndex);
    }
}

如果您不使用更新方法或每帧调用的方法(例如 OnTriggerStay()),您将无法检测到用户是否实际按下了键。