- Home /
Coroutine mystery (for a noob)
For some reason the length of the animation in the first coroutine is carried over to the second. The first animation (Load_Bow) goes for 1.5 seconds (or whatever units 'length' refers to), and the second animation (Draw_Bow) goes for 1 second.
As a result of this, the second animation repeats as it continues until the length of the first animation is complete. I do not know why my code is doing this and I'm assuming I've missed something pretty important about how co-routines work.
public IEnumerator LoadBow()
{
this.gameObject.GetComponent<Animation>().CrossFade("Load_Bow");
yield return new WaitForSeconds(this.gameObject.GetComponent<Animation>()["Load_Bow"].length);
aimStates = AimStates.Draw;
}
public IEnumerator DrawBow()
{
this.gameObject.GetComponent<Animation>().CrossFade("Draw_Bow");
yield return new WaitForSeconds(this.gameObject.GetComponent<Animation>()["Draw_Bow"].length);
aimStates = AimStates.Aim;
}
public void Aiming()
{
moveTarget.SetActive(false);
switch(aimStates)
{
case AimStates.Load:
StartCoroutine(LoadBow());
break;
case AimStates.Draw:
StartCoroutine(DrawBow());
break;
It's part of a larger FS$$anonymous$$ in the same script. The overall FS$$anonymous$$ method is called from another script. Do you think I need to include all that code?
Yeah including the Ai$$anonymous$$g() call would be a good idea, you probably don't want to be calling that every frame if you are.
Thanks guys. Crossfading was a problem. As was having no condition in the load state to say when to activate the coroutine.
Answer by nullgobz · Jul 30, 2015 at 01:36 PM
The coroutines wont block code calling it. If your calling these coroutines multiple times in for example an Update function. Then you will get the behaviour you have right now. You need to make sure that you only call a coroutine when you acually want it to start. A coroutine only blocks statements after the yield within the function itself.
Example:
public IEnumerator LoadBow()
{
// Play Animation Here!
aimStates = AimStates.Draw;
yield return new WaitForSeconds(1.0f);
// Call next animation here!
DrawBow();
}
// You could make this a coroutine if i you need something to happen after its done
public void DrawBow()
{
// Play Animation Here!
aimStates = AimStates.Aim;
}
Thank you. I stopped update from calling it every frame by controlling the LoadBow coroutine with a bool. It works now. meat5000 pointed out that crossfading the animations could also be causing a problem in this instance (and it was).
Your answer
Follow this Question
Related Questions
Animation with minimum length? 1 Answer
CORoutine does not completely stop 1 Answer
Wait for animation to finish? Animator.SetBool... 1 Answer