::If you run into this problem when implementing Part 12 of the series:
View post on imgur.com
This can be fixed by fixing the Fade() function by including a check to see if the CanvasGroup still exists, before trying to adjust its alpha value:
// Coroutine that causes a whole Canvas Group to fade in / fade out.
protected virtual IEnumerator Fade(float duration, int direction = 1)
{
WaitForSecondsRealtime w = new WaitForSecondsRealtime(updateFrequency);
// Don't play as long as another animation is playing on this.
while (isAnimating) yield return w;
isAnimating = true;
float currentDuration = duration;
group.alpha = direction > 0 ? 0 : originalAlpha;
gameObject.SetActive(true);
while (currentDuration > 0)
{
yield return w;
float timeScale = GetTimeScale();
if (timeScale <= 0) continue;
currentDuration -= w.waitTime * timeScale;
float ratio = currentDuration / duration;
if(group) group.alpha = (direction > 0 ? 1f - ratio : ratio) * originalAlpha;
}
if(group) {
group.alpha = direction > 0 ? originalAlpha : 0;
if (direction < 0) gameObject.SetActive(false);
}
isAnimating = false;
}
The reason this happens is because of the yield return w; in the while loop. During the wait, if another script destroys our CanvasGroup or the GameObject containing it, trying to access group.alpha, or the containing gameObject will cause the MissingReferenceException, and including the highlighted sections above prevent that from happening.