- Home /
Coroutine doesn't work when called from another method.
Hello, I've this very simple piece of code:
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void Animation()
{
StartCoroutine(Delay());
}
IEnumerator Delay()
{
Debug.Log("InDelay");
Root.SetTrigger("Change");
for (int k = 0; k < 12; k++)
{
Bar[k].SetTrigger("Change");
yield return new WaitForSeconds(1f);
}
}
The problem here, is that when I call the "Animation()" method, the coroutine doesn't start at all, but if I move the "StartCoroutine" method to the Start() method, it starts correctly.
How can I start my coroutine just calling my "Animation()" method, please? Thanks.
Answer by Bunny83 · Aug 27, 2019 at 12:21 PM
I don't see any issue here. Are you sure your "Animation" method actually gets calls? How do you call it? From another script? Are you sure you reference the correct object? Maybe that other script references a prefab and not the instance in the scene? Coroutines can only run on instances in the scene.
Try adding this line to your Animation method:
Debug.Log("Animation() was called", gameObject);
Do you see this log in the console? If yes just click on the log message in the console. It will ping / highlight the gameobject this script is attached to. If it's not a gameobject in the scene, you called the method on the wrong object. Since we don't have all that information about your project we can't help you any further without more information.
Answer by PKU_DZY · Aug 27, 2019 at 12:40 PM
Coroutine will be excuted only when the component is enabled and gameobject is active in hierchy. Check those conditions!
Answer by OldHarryMTX · Apr 04, 2020 at 07:11 PM
I have got the same issue. My Coroutine doesn't start if StartCoroutine is called in a different method than Start(). I'm sure that the methods are called properly since i have tested it linking the compiler to unity and setting some arrest points.
Your answer
Follow this Question
Related Questions
Problem with coroutine 2 Answers
yield return new WaitForSeconds () not working 1 Answer
Need Help with a Null Reference 1 Answer
OnCollisionEnter as IEnumerator problem (WaitForSecond) 2 Answers