在公共静态函数Unity中调用Invoke

时间:2020-02-01 11:12:34

标签: unity3d invoke static-functions

我遇到了我不理解的错误。我的代码的简化版本:

using UnityEngine;
public class RunLater : MonoBehaviour
{
    public static void Do()
    {
        Invoke("RunThisLater", 2.0f);
    }

    public void RunThisLater()
    {
        Debug.Log("This will run later");
    }

}

2 个答案:

答案 0 :(得分:0)

您可以将其作为这样的参数传递:

public class RunLater : MonoBehaviour
{            
    public static void Do(RunLater instance)
    {
        instance.Invoke("RunThisLater", 2.0f);
    }

    public void RunThisLater()
    {
       Debug.Log("This will run later");
    }
}

答案 1 :(得分:-1)

一种方法是让类的静态部分存储对自身的MonoBehaviour引用。像这样:

public class RunLater : MonoBehaviour
{
    public static RunLater selfReference = null;

    public static void Do()
    {
        InitSelfReference();
        selfReference.DoInstanced();
    }

    static void InitSelfReference()
    {
        if (selfReference == null)
        {
            // We're presuming you only have RunLater once in the entire hierarchy.
            selfReference = Object.FindObjectOfType<RunLater>();
        }
    }

    public void DoInstanced()
    {
        Invoke("RunThisLater", 2f);
    }

    void RunThisLater()
    {
        Debug.Log("This will run later");
    }
}

您现在可以在其他gameObjects代码中的任何位置调用RunLater.Do()。祝你好运!

相关问题