Can't stop a Coroutine with a Coroutine Reference ?!
It's simple as it sounds. I use it on a UI text element to flash when any "Up" button is pressed.
It's start successfully, but it won't stop no matter what ?
Here is my very simple code:
[SerializeField] Color BlickingColor = new Color(0, 0, 255);
[SerializeField] float BlinkingRate = 0.1f;
private Coroutine AnimationCoroutine;
public Color DefaultColor { get; set; }
public Color TextFontColor { get { return this.GetComponent<Text>().color; } set { this.GetComponent<Text>().color = value; } }
void Start()
{
DefaultColor = TextFontColor;
}
void Update()
{
float Axis = Input.GetAxis("Vertical");
if (Axis > 0)
{
StartAnimation();
}
else if (Axis < 0)
{
if (AnimationCoroutine != null)
{
StopAnimation();
}
}
}
void StartAnimation()
{
AnimationCoroutine = StartCoroutine(HighlightButton());
}
void StopAnimation()
{
StopCoroutine(AnimationCoroutine);
TextFontColor = DefaultColor;
}
IEnumerator HighlightButton()
{
while (true)
{
var nextColor = TextFontColor == BlickingColor ? DefaultColor : BlickingColor;
yield return new WaitForSeconds(BlinkingRate);
TextFontColor = nextColor;
yield return new WaitForSeconds(BlinkingRate);
}
}
Is there a special case with UI or something ?
I should note somethings before you answer to get things clear:
Trying to store the IEnumerator reference and stop it won't work either
Using "methodName" string won't work too
The only "solution" is to StopAllCoroutines function, which is not what I'm looking for.
Is StopAnimation
called? (Use a simple Debug.Log
to find out).
You said I use it on a UI text element to flash when any "Up" button is pressed.
but according to your code, you need to press the "Down" button to make the animation stop ( else if (Axis < 0)
)
I press one of the down buttons (e.g. 'S' key or "DownArrow" key) to stop the Corotine, and in Debug mode the break point is activated when I do so.
However, the Corotine doesn't stop. Only if I replace the line with "StopAll....." function, then it works fine
Your answer
![](https://koobas.hobune.stream/wayback/20220612202610im_/https://answers.unity.com/themes/thub/images/avi.jpg)