- Home /
how to restart coroutine
Hello, I cant understand how can I stop my coroutinein my script. The thing is that I initialize my coroutine, and start it, but i call my function a lot of times, and I have to stop my previous coroutine before its unitializing. Here is the code: private void OnChanged(float s) { var a = TransmitCurrentHealth(s);
//StopAllCoroutines();
StopCoroutine(a);
StartCoroutine(a);
}
private IEnumerator TransmitCurrentHealth(float currentHealthValue)
{
while (_slider.value != currentHealthValue)
{
_slider.value = Mathf.MoveTowards(_slider.value, currentHealthValue, _smoothness * Time.deltaTime);
yield return null;
}
}
It works perfectly with StopAllCoroutine, but as I know it is a bad practice to use it. Even typing StopCoroutine after StartCoroutine wont help - in this way my coroutine will work just once
Answer by andrey231102 · Aug 28, 2021 at 01:06 PM
private IEnumerator _coroutine;
private void OnChanged(float healthValue) { if (_coroutine!= null) StopCoroutine(_coroutine);
_coroutine = TransmitCurrentHealth(healthValue);
StartCoroutine(_coroutine);
}
private IEnumerator TransmitCurrentHealth(float currentHealthValue)
{
while (_slider.value != currentHealthValue)
{
_slider.value = Mathf.MoveTowards(_slider.value, currentHealthValue, _smoothness * Time.deltaTime);
yield return null;
}
}
Answer by Vivien_Lynn · Aug 28, 2021 at 09:57 AM
You need to store your Coroutine in a variable, and then Stop that specific Coroutine, using that variable.
In your example, you should probably instantiate the variable private IEnumerator myRoutine;
at the top of your class.
When you want to start your Coroutine, you store it in that variable: myRoutine = StartCoroutine(TransmitCurrentHealth(a));
To stop it, you just call StopCoroutine(myRoutine);
(wyi the example in the docs is sadly a bit short, and does not cover how to stop a Coroutine: https://docs.unity3d.com/ScriptReference/Coroutine.html)
Thank you very much!!! I have instantiated the IEnumerator and then changed my code. I will left the code here, hope it will help someone