- Home /
Coroutine exists after while loop, gameObject isn't being deleted
Hello, I'm having trouble with a coroutine. I'm noticing that the coroutine stops running when it completes a while loop. The most common solution I'm finding online is to make sure that the gameObject calling the coroutine isn't being destroyed, and it definitely isn't.
The thing that confuses me the most is that I tried using debug breaks to see what was going on and when I put one in the loop guard and step through each iteration of the loop manually, it works fine. When the game runs normally, the code after the while loop doesn't get executed. Let me know if you come up with any insights. The issue is with the while (curVal != targVal)
section.
public static void ShowScene(bool show, float speed = 1f, bool smooth = false, Texture2D transitionEffect = null) {
if (transitioningOverlay != null)
instance.StopCoroutine(transitioningOverlay);
sceneVisible = show;
if (transitionEffect != null)
instance.overlayImage.material.SetTexture("_AlphaTex", transitionEffect);
transitioningOverlay = instance.StartCoroutine(TransitioningOverlay(show, speed, smooth));
}
static Coroutine transitioningOverlay = null;
static IEnumerator TransitioningOverlay(bool show, float speed, bool smooth) {
float targVal = show ? 1f : 0f;
float curVal = instance.overlayImage.material.GetFloat("_Cutoff");
while (curVal != targVal) {
curVal = smooth ? Mathf.Lerp(curVal, targVal, speed * Time.deltaTime)
: Mathf.MoveTowards(curVal, targVal, speed * Time.deltaTime);
instance.overlayImage.material.SetFloat("_Cutoff", curVal);
yield return new WaitForEndOfFrame();
}
transitioningOverlay = null;
NovelController.instance.Next();
}
Answer by cwalshwarder · Jul 31, 2020 at 11:41 PM
Are you unloading a scene? Maybe the gameObject calling the coroutine really is destroyed, but it isn't null because it's still being referenced. That's probably not the problem, but I guess try doing DontDestroyOnLoad(instance) to make sure it's not destroyed.