为什么AddListener不回叫?

时间:2019-04-01 18:39:20

标签: c# unity3d

我试图在实例化时通过代码将UnityEvent侦听器添加到另一个脚本中。但是,永远不会调用回调方法。

我在脚本UIFader中放入了一条调试语句,并且打印输出显示UnityEvent不为null,因此它可以看到侦听器。但是没有调用UIManager中的回调方法。

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;
            }
        }

1 个答案:

答案 0 :(得分:3)

您调用OnFadeInComplete而不是OnFadeOutComplete

顺便说一句,如果您的Unity版本支持C#6.0,则可以编写

OnFadeOutComplete?.Invoke();

它检查是否为null并防止此类错误。

在旧版本中,您可以为ActionAction <T>编写扩展方法:

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

并写为

OnFadeOutComplete._();
相关问题