You need to call StopCoroutine
with a reference to the same Coroutine
returned by StartCoroutine
, like this:
private Coroutine loopCoroutine;
public void LoopButton()
{
if (lb == 1)
{
StopCoroutine(loopCoroutine);
tb--;
}
else
{
loopCoroutine = StartCoroutine(AutoLoop());
tb++;
}
}
To use this approach, change your AutoLoop
method to use a while loop rather than a starting another AutoLoop
coroutine at the end of the method. Otherwise, you will not be able to stop this new coroutine that is started at the end of AutoLoop
.
IEnumerator AutoLoop()
{
while(true)
{
slider.value = slider.minValue;
while (slider.value < slider.maxValue)
{
slider.value++;
yield return new WaitForSeconds(0.5f);
}
}
}
For an alternate solution, as another user commented, it's also possible to stop the coroutine via a boolean flag:
private bool stopLoop;
public void LoopButton()
{
if (lb == 1)
{
stopLoop = true;
tb--;
}
else
{
stopLoop = false;
StartCoroutine (AutoLoop ());
tb++;
}
}
IEnumerator AutoLoop()
{
slider.value = slider.minValue;
while (slider.value < slider.maxValue && !stopLoop)
{
slider.value++;
yield return new WaitForSeconds(0.5f);
}
if (!stopLoop)
{
StartCoroutine(AutoLoop());
}
}
However, using Unity's StopCoroutine
is preferable to using a boolean flag for readability & cleanliness.