Hi all,
I’ve run into the following problem with co-routines. I have a need in my game to be able to run co-routines from a script which does not inherit from Mono Behavior. I do this in the following fashion: I have a helper class, which inherits from Mono Behavior, whose only responsibility is to run co-routines. It looks something like this:
public class CoroutineHelper : MonoBehaviour
{
public delegate IEnumerator CoroutineMethod ();
public Coroutine StartCoroutineDelegate (CoroutineMethod coroutineMethod)
{
return StartCoroutine ("RunCoroutine", coroutineMethod);
}
}
Whenever I want to execute a co-routine method from a non-Mono Behavior class, I do this:
public class NonMonoBehavior
{
private static CoroutineHelper _coroutineHelper;
NonMonoBehavior()
{
_coroutineHelper = GameObject.Find ("ScriptsHub").GetComponent<CoroutineHelper> ();
}
public TestMethod()
{
// Call a co-routine method
CoroutineHelper.CoroutineMethod doAfterDelayDelegate = doAfterDelay;
_coroutineHelper.StartCoroutineDelegate (doAfterDelayDelegate);
DebugConsole.log("This SHOULD get printed after 5 seconds, but it does not.");
}
// The co-routine method
IEnumerator doAfterDelay ()
{
yield return new WaitForSeconds (5.0);
// Do something here
DebugConsole.log("This DOES get printed after 5 seconds.");
}
}
As you can probably surmise, my CoroutineHelper script is attached to an empty game object called ScriptsHub. So this works well, except for the fact there is no way to know when the co-routine method ends. For example, the output of the above would look like this:
This SHOULD get printed after 5 seconds, but it does not.
This DOES get printed after 5 seconds.
So, as you can see, the problem is that my CoroutineHelper class cannot currently tell the rest of the code when CoroutineMethod has ended. The first output line above gets printed instantly. In other words, I need a way to know, in method TestMethod above, when the co-routine method doAfterDelay has finished executing. Any ideas how to do that?