Do coroutines and Invoke not work properly outside of the Start() and Update() methods?
I have been trying to very simply execute a method at some later time, but it never works.
With Invoke, I’m simply doing:
class Research : MonoBehaviour {
public void Begin() {
Invoke("End", 1);
}
public void End() {
Debug.Log("Ended");
}
}
With a coroutine, I’ve tried just doing:
class Research : MonoBehaviour {
public void Begin() {
StartCoroutine(End());
}
IEnumerator End() {
yield return new WaitForSeconds(1);
Debug.Log("Ended");
yield return null;
}
}
Then I have another class with a method which calls Begin(). I use an instance of this GameManager class to start things, i.e. by calling gameManager.Research().
class GameManager : MonoBehaviour {
public Research research;
void Start() {
research = gameObject.AddComponent<Research>();
}
public bool Research() {
research.Begin();
}
}
I never see the “End” message get printed. I checked if the object was being destroyed, but it isn’t. I haven’t been able to figure out why such a simple example doesn’t work. I have coroutines working fine elsewhere in my program but they are called from a Start() method, but I haven’t been able to find any documentation that says coroutines are valid only at certain times.
Even within the Update() method, it seems if Invoke isn’t called directly it doesn’t work. To clarify, this works:
void Update() {
Invoke("End", 1);
}
but this doesn’t:
public bool startInvoke = false;
void Update() {
if (startInvoke) {
Invoke("End", 1);
}
}
// something sets startInvoke = true;
To clarify, I am getting an instance of GameManager and calling Research on it, i.e. gameManager.Research(), which ends up calling Begin().