Jeremy Voss
Jeremy Voss

Reputation: 43

Why is AddListener not calling back?

I'm trying to add a UnityEvent listener to another script through code when I instantiate it. However the callback method is never being called.

I've put a debug statement in my script UIFader, and the printout is showing that the UnityEvent is not null, so it sees listeners. Yet the callback method in UIManager isn't being called.

UIManager.cs

public void SpawnInformationWindow()
    {
        if (canvas == null || InformationWindowPrefab == null)
        {
            return;
        }

        GameObject informationWindow = Instantiate(InformationWindowPrefab, canvas, false);
        informationWindow.GetComponent<UIFader>().OnFadeOutComplete.AddListener(SpawnTermsOfUseWindow);
    }

    public void SpawnTermsOfUseWindow()
    {
        Debug.Log("THIS RAN!");

        if (canvas == null || TermsOfUseWindowPrefab == null)
        {
            return;
        }

        GameObject termsOfUseWindow = Instantiate(TermsOfUseWindowPrefab, canvas, false);
    }

UIFader.cs

void CompleteFadeOut()
        {
            Debug.Log("Fadeout Complete! " + OnFadeOutComplete == null);

            if (OnFadeOutComplete != null)
                OnFadeInComplete.Invoke();

            if (destroyOnFadeOut)
                Destroy(gameObject);
            else if (mode == FadeMode.PingPong)
                FadeIn();
            else
            {
                mode = FadeMode.None;
                currentState = FadeMode.None;
            }
        }

Upvotes: 0

Views: 435

Answers (1)

trollingchar
trollingchar

Reputation: 790

You invoke OnFadeInComplete instead of OnFadeOutComplete.

By the way, if your Unity version supports C# 6.0, you can write

OnFadeOutComplete?.Invoke();

It checks for null and protects from such bugs.

In older versions you can write extension method for Action and Action <T>:

public static class ActionExtension {
    public static void _ (this Action f) {
        if (f != null) f();
    }
}

and write something as

OnFadeOutComplete._();

Upvotes: 3

Related Questions