繁体   English   中英

我不能直接调用 function

[英]i can't invoke a function directly

{

    bool GameEnd = false;

    public float restartDelay = 1f;

    public void GameOver()
    {
        if(GameEnd == false)
        {
            GameEnd = true;
            Debug.Log("GAMEOVER");
            Invoke("Restart", restartDelay);
        }
        
        void Restart()
        {
            SceneManager.LoadScene(SceneManager.GetActiveScene().name);
        }

    }    
}

我想延迟调用“重启”,但显示“无法调用”

怎么了?

在 class scope 中声明这两种方法:使用 System.Collections.Generic; public class YourClass: MonoBehaviour { //大概是 monobehaviour

    bool GameEnd = false;
    public float restartDelay = 1f;

    private IEnumerator coroutine;

    void Start() {
        coroutine = Restart(); 
    }
    public void GameOver()
    {
        if(GameEnd == false)
        {
            GameEnd = true;
            Debug.Log("GAMEOVER");
            Invoke("Restart", restartDelay);
        }
        StartCoroutine(coroutine);
    } 

    IEnumerator Restart()
    {
        yield return new WaitForSeconds(1f);
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }
}

未调试,exmaple 只是为了向您展示它是如何工作的。

您的方法在GameOver方法中是本地的(== 嵌套)。

为了使用Invoke ,它需要在 class 级别 scope 上

bool GameEnd = false;

public float restartDelay = 1f;

public void GameOver()
{
    if(GameEnd == false)
    {
        GameEnd = true;
        Debug.Log("GAMEOVER");
        Invoke(nameof(Restart), restartDelay);
    }
}   

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

否则 Unity 将找不到它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM