Yeah, I'm literally stuck on a simple Coroutine. In my Unity game I've been trying to figure out how to use something like this in a public static void:
StartCoroutine(ExampleCoroutine())
I understand that there is no way to use that line in a public static void, but I'm trying to find a workaround that would do the same thing. So far the internet hasn't been a help, but the closest I've gotten to my problem being solved was something about creating an instance. I didn't understand it because I am a mere novice, but it might be a lead as this is the error I get while creating:
error CS0120: An object reference is required for the non-static field, method, or property 'MonoBehaviour.StartCoroutine(IEnumerator)'
The IEnumerator that the Coroutine starts is marked public static, if that helps at all. Thank you for your time and humouring my stupidity
EDIT: I was asked to show more code, so here I go!
public static void NeedsToBeAccessedElsewhere()
{
StartCoroutine(NeedsDeley());
//Do Stuff
}
public static IEnumerator NeedsDelay()
{
//results
}
A coroutine always needs an instance of MonoBehaviour that is responsible for executing it. Therefore StartCoroutine is not a static but an instance method and has to be called on an instance of MonoBehavior.
Thus if your method is static you either have to pass in a MonoBehaviour reference like e.g.
public static void NeedsToBeAccessedElsewhere(MonoBehaviour instance)
{
instance.StartCoroutine(NeedsDeley());
}
public static IEnumerator NeedsDelay()
{
//results
}
Or as a fallback you could make sure there is a default behavior that is created on demand
public class CoroutineExecuter : MonoBehaviour { }
and do
private static CoroutineExecuter instance;
public static void NeedsToBeAccessedElsewhere()
{
if(!instance)
{
instance = FindObjectOfType<CoroutineExecuter>();
if(!instance)
{
instance = new GameObject ("CoroutineExecuter").AddComponent<CoroutineExecuter>();
}
}
instance.StartCoroutine(NeedsDeley());
}
public static IEnumerator NeedsDelay()
{
//results
}
Note, however, in general: You commented // Do stuff but have in mind that calling. StartCoroutine is terminated immediately and does not delay the method calling it. If this was your plan you should rather pass in a callback like
public static IEnumerator NeedsDelay(Action afterDelay)
{
yield return new WaitForSeconds(3f);
afterDelay?.Invoke();
}
and use it like e.g.
instance.StartCoroutine(NeedsDelay(() =>
{
Debug.Log("Delay has finished");
}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With