- Home /
StartCoroutine fires once
The following snippet is inside a monobehavior. FadeOut() is called externally. For whatever reason, it only returns a value to the callback to the first time.
public void FadeOut(Action<float> callback)
{
StartCoroutine(FadeOutC(callback));
}
private float _fadeOut = 1;
private IEnumerator FadeOutC(Action<float> callback)
{
if(_fadeOut > 0)
{
yield return new WaitForEndOfFrame();
var value = _fadeOut -= Time.deltaTime;
callback(value);
Debug.Log(_fadeOut);
}
else
{
callback(0);
StopCoroutine("FadeOutC");
_fadeOut = 1;
}
}
You're not decreasing _fadeOut at all, you're making a temporary variable and decreasing that, but that won't do anything. (Also "`var value = _fadeOut -= Time.deltaTime;`" should use - rather than -=.) Unless you need to wait specifically for the end of the frame for some reason, use the standard "`yield return null;`" to wait a frame rather than WaitForEndOfFrame. StopCoroutine will not work unless the coroutine is started with the string overload, but, as mentioned by OP_toss, you don't need it anyway.
Answer by OP_toss · Apr 10, 2013 at 02:25 AM
Change
if(_fadeOut > 0)
to
while(_fadeOut > 0)
and remove the StopCoroutine call. It will stop on its own or you can yield break if necessary.
Coroutines are just functions that run once and are able to be split up. Its up to you to make them continually call or to loop or w/e.
EDIT: Agreed with erik5h5, replace your yield with a yield return null
. This will return on the next frame.
Your answer
Follow this Question
Related Questions
Coroutines and states 1 Answer
Startcoroutine not working second time 2 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
I can't start a coroutine. I get a weird message from visual studio 1 Answer