- Home /
Coroutine stops working after first run
Premise:
I've got a button (made of a quad) working properly that references an animation curve to animate when clicked.
Issue
I can click my button once, and it'll run through the coroutine that uses the animation curve to animate it. But after that, I can't get it to trigger again. I know its still receiving the click events from the log, but the coroutine won't run after the first time its run. Any ideas why? Code for the button script below:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Button : MonoBehaviour {
public AnimationCurve curveAnim;
public float posDisplacement;
public float speed;
public void KickBack(){
StartCoroutine (kickback());
}
IEnumerator kickback(){ //animation coroutine
float curveTime = 0f;
float curveAmount = curveAnim.Evaluate (curveTime);
while (curveAmount < 1.0f) {
curveTime += Time.deltaTime * speed;
curveAmount = curveAnim.Evaluate (curveTime);
transform.position = new Vector3 (transform.position.x, transform.position.y, curveAmount*posDisplacement);
yield return null;
}
}
//Button events called from "gameObject.SendMessage." in another script
void OnTouchDown(){
Debug.Log ("Touch Down!");
}
void OnTouchUp(){
Debug.Log ("Touch Up!");
KickBack ();
}
void OnTouchStay(){
}
void OnTouchExit(){
}
}
Answer by FlaSh-G · Aug 11, 2017 at 08:50 PM
It's just a guess because the code looks mostly fine, but I think your first Coroutine never stops and happens to be executed after all following Coroutine calls forever after.
The coroutine ends when
curveAmount < 1.0f
is the case, and depending on how you set your AnimationCurve, this might be true forever.
I suppose you initially wanted to check
curveTime < 1.0f
anyway, which would be reliable to go over 1 sooner or later (unless speed is less than or equal to 0).
Yup! Thats exactly what it was. I was referencing the amount ins$$anonymous$$d of time. Thanks!
Your answer
Follow this Question
Related Questions
Using a coroutine to wait for a button press? 1 Answer
Wait for button response in coroutine? 2 Answers
Is it possible to start a coroutine using a button from the new UI system (4.6) 1 Answer
AnimationCurve as fixed time rather than portion of time? 1 Answer
I am trying to take away some health from a slider using a coroutine, but it takes away too much 1 Answer