invoke() Function in unity [duplicate]

我怕爱的太早我们不能终老 提交于 2021-02-05 12:19:42

问题


Its almost my first time using C sharp and unity. I am trying to use invoke() function in unity but its giving the error

"Trying to Invoke method: EndGame.Restart1 couldn't be called."

public class EndGame : MonoBehaviour
{ 
    bool GameHasEnded = false;
    public float Timer = 1f;
    
    public void endgame() 
    {        
        if (!GameHasEnded) 
        {
            GameHasEnded = true;
            Debug.Log("GameOver");
            Invoke("Restart", Timer);
        }
   
        void Restart()
        { 
            SceneManager.LoadScene(SceneManager.GetActiveScene().name);
        }
    }
}

回答1:


  • You are trying to Invoke a local method that is nested inside of another method endgame.

    Afaik MonoBehaviour.Invoke can only call methods on class level.

  • It also is either a typo here or in your original code but Restart1 doesn't exist only Restart. To avoid typos in name based code I would use nameof

Your code should rather look like

public class EndGame : MonoBehaviour
{
    private bool GameHasEnded = false;

    // Timer is strange name for that
    // I would suggest "Delay"
    public float Delay = 1f;

    public void endgame()
    {         
        if (!GameHasEnded)
        {
            GameHasEnded = true;
            Debug.Log("GameOver");

            // In general in order to avoid typos I would prefer to use "nameof"
            Invoke(nameof(Restart), Delay);
        }
    }

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


来源:https://stackoverflow.com/questions/65543031/invoke-function-in-unity

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!