1

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

}
  • Right "runthislater" is not static, therefore inside your class you have no instance to call runthislater on.. – BugFinder Feb 01 '20 at 11:32
  • BugFinder so what should i do now? make RunThisLater static as well or remove Static from Do funciton? – hasnain nadeem Feb 01 '20 at 11:54
  • 1
    well it will in part depend on what you intend to do with it later..... – BugFinder Feb 01 '20 at 12:01
  • You can pass a reference to to the owning object... For example when you call Do you could pass a parameter to your monobheaviour like Do(myBehaviour) of course you would need to modify your method to take in a parameter – Jonathan Alfaro Feb 01 '20 at 17:19

2 Answers2

0

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");
    }
}
Jonathan Alfaro
  • 4,013
  • 3
  • 29
  • 32
  • and if I wanted to call this from another class then how I'm gonna call? – hasnain nadeem Feb 02 '20 at 14:03
  • then you have to get the instance from hierarchy.... and pass it in. No matter how you do it; if you want to call an instance method from inside a static method you WILL need access to the instance. The other choice you have is to NOT make your method static and just get a reference to your instance from the other class using GetComponent or Find or FindWithTag... or similar. – Jonathan Alfaro Feb 02 '20 at 14:38
-1

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!

Philipp Lenssen
  • 8,818
  • 13
  • 56
  • 77