首页 > 解决方案 > 声明了本地函数“RestartGame”但从未使用过 Assembly-CSharp

问题描述

我真的需要帮助,当我在 C# 中调用 Invoke 时,出现以下错误:

声明了本地函数“RestartGame”但从未使用过 Assembly-CSharp

我真的不知道为什么会这样,但这里是代码:

使用 UnityEngine;使用 UnityEngine.SceneManagement;

公共类 GameManager : MonoBehaviour { bool gameHasEnded = false;

public float restartDelay = 2f;
public void EndGame()
{
    if (gameHasEnded == false)
    {
        gameHasEnded = true;
        Debug.Log("GAME OVER");
        Invoke("RestartGame", restartDelay);
    }

    void RestartGame ()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }
}

}

标签: unity3ddelayinvoke

解决方案


unity manual:为了获得更好的性能和可维护性,请改用 Coroutines。 https://docs.unity3d.com/ScriptReference/MonoBehaviour.Invoke.html

尝试这样的事情:

using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;

public class GameManager : MonoBehaviour
{
    bool gameHasEnded = false;

    public float restartDelay = 2f;
    private IEnumerator coroutine;

    public void EndGame()
    {
        if (gameHasEnded == false)
        {
            gameHasEnded = true;
            Debug.Log("GAME OVER");

            coroutine = RestartDelayed(restartDelay);
            StartCoroutine(coroutine);
        }

        void RestartGame()
        {
            SceneManager.LoadScene(SceneManager.GetActiveScene().name);
        }

        IEnumerator RestartDelayed(float delay)
        {
            yield return new WaitForSeconds(delay);
            RestartGame();
        }

    }
}

https://docs.unity3d.com/ScriptReference/MonoBehaviour.StartCoroutine.html


推荐阅读