【问题标题】:i can't invoke a function directly我不能直接调用函数
【发布时间】:2021-02-11 10:34:06
【问题描述】:
{

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

    }    
}

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

怎么了?

【问题讨论】:

  • 因为它是本地函数?你打错了,它不应该是本地的?
  • 我必须做一个公共功能?
  • 现在你的“重启”方法是本地的(只能访问)周围的 GameOver 方法

标签: c# visual-studio unity3d


【解决方案1】:

在类范围内声明这两个方法: 使用 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);
    }
}

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

【讨论】:

  • 是的,但是这样没有延迟,我需要延迟1秒
  • 然后试试coroutine。答案中的示例
  • 未调试,希望它足够清晰,可以指导您:)
  • Assets\GameManager.cs(27,5): error CS0246: The type or namespace name 'IEnumerator' could not be found(你是否缺少 using 指令或程序集引用?)现在它说这个,对不起,我是初学者。也许我需要使用图书馆
  • 尝试添加using System.Collections.Generic。已更新答案
【解决方案2】:

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

为了使用Invoke,它需要在类级别范围内,例如

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 将找不到它。

【讨论】:

  • 似乎我在语言功能方面方式落后于时代......本地功能什么时候成为一个东西?
  • @Immersive since c# 7 尽管这个概念本身已经存在于许多语言中;)
猜你喜欢
  • 1970-01-01
  • 2012-03-04
  • 2021-08-10
  • 2020-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多