Forum begins after the advertisement:


[Part 12] MissingReferenceException with CanvasGroup in UIScreen

Home Forums Video Game Tutorial Series Creating a Metroidvania in Unity [Part 12] MissingReferenceException with CanvasGroup in UIScreen

Viewing 1 post (of 1 total)
  • Author
    Posts
  • #18010
    Terence
    Level 31
    Keymaster
    Helpful?
    Up
    0
    ::

    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.

Viewing 1 post (of 1 total)
  • You must be logged in to reply to this topic.

Go to Login Page →


Advertisement below: