Calling Invoke within a public static function Unity

1.7k views Asked by At

I'm getting an error that I don't understand. The simplified version of my code:

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

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

}
2

There are 2 answers

4
Philipp Lenssen On

One approach is to have the static parts of the class store a MonoBehaviour reference to itself. Like so:

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

You would now be able to call RunLater.Do() from anywhere in your code of other gameObjects. Good luck!

2
Jonathan Alfaro On

You can pass it in as a parameter like this:

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

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