Fade Specific UI

Hello,

I have a fade script. It is working but I do not understand it completely and it prevents me from making it simple. Here what it looks like:

    IEnumerator FadeInCombatBackground()
    {
        CanvasGroup canvasGroup = GetComponent<CanvasGroup>();
        while (canvasGroup.alpha < 1)
        {
            canvasGroup.alpha += Time.deltaTime / 0.5f;
            yield return null;
        }

        yield return null;
    }

I call it from a public void:

    public void TestFadeInCombatBackground()
    {
        combatBackground.SetActive(true);
        StartCoroutine(FadeInCombatBackground());
    }

So I want to fade my “combatBackground”.

When I call it via an On Click action, it works

5387829--546312--upload_2020-1-19_22-8-42.png

But when I call it from a script, it does not work.

fade.TestFadeInCombatBackground();

I believe that the On Click action works because it knows what I want to fade as the UI object is directly attached to the action.

And I believe the script does not work because it does not know what I want to fade.

What do you think? Any solution?

Thank you

Hello ^^ I am still on it if someone has an idea :stuck_out_tongue:

Are you getting any errors? The way the code is written, the way it “knows” what to fade is it grabs the CanvasGroup attached to the same GameObject this fade script is attached to. Whatever CanvasGroup component is attached, that is the one it will fade. If GetComponent() returns null, such as when no such component exists attached to that same GameObject, then you’ll get a null reference error on line 5 when you try to access it.