- Home /
Confused on Coroutines and/or For Loops
I am a relatively amateur coder, at least for C#, and I am getting confused on trying to use coroutines. I can probably do this a different way but I wanted to use coroutine to learn. I have pasted code below, can someone please explain why this does not work? I would expect it to, when "Attack1" is hit, run the coroutine which should set my bools to true unless it is on the last one, which will set them false. Essentially I am just trying to use it as a timer running at the same time as Update. I know my input is working because I have changed comments in 'Attack()' to force the animation to run, so I think it is in my for or Bite(). Thank you for any input.
void Attack()
{
if (Input.GetButton ("Attack1"))
{
//biteArea.gameObject.SetActive (true);
//PlayerAnimator.SetBool ("Bite", true);
Bite ();
}
}
IEnumerator Bite()
{
for (var i = 1.0f; i >= 0f; i -= 0.1f)
{
if (i >= 0.1f)
{
biteArea.gameObject.SetActive (true);
PlayerAnimator.SetBool ("Bite", true);
}
else
{
biteArea.gameObject.SetActive (false);
PlayerAnimator.SetBool ("Bite", false);
}
}
yield return new WaitForSeconds (0.1f);
}
Answer by gjf · Mar 18, 2017 at 08:56 PM
first of all, if you want to run Bite() as a co-routine, you should call it like this:
StartCoroutine(Bite());
then, and i'm (somewhat foolishly) assuming that you want your for loop to wait 0.1 seconds between iterations, right?
if so, move your yield statement so that inside the loop construct - right now, it's outside and will iterate, wait 0.1 seconds, then exit. probably not what you want.
Your answer