Unity添加第二个PersistentListener不起作用

时间:2017-08-09 11:25:18

标签: c# unity3d

我创建了一个自定义编辑器,可以自动创建游戏对象及其组件,并自动将侦听器添加到事件中。

但是向事件添加两个持久侦听器不起作用,但是如果我将它分开,它将起作用。

[MenuItem("GameObject/Create Animation/With SFX", false, -1)]
static void CreateAnimationWithSFX()
{
    GameObject go = new GameObject("animationWithSFX");
    go.transform.SetParent(Selection.activeTransform);

    AudioSource audioSource = go.AddComponent<AudioSource>();
    audioSource.playOnAwake = false;
    AudioMixer mixer = Resources.Load("Master") as AudioMixer;
    audioSource.outputAudioMixerGroup = mixer.FindMatchingGroups("SFX")[0];

    SceneAnimationEvent script = go.AddComponent<SceneAnimationEvent>();

    // audioSource.Play
    script.Events = new UnityEvent();
    UnityAction methodDelegate = System.Delegate.CreateDelegate (typeof(UnityAction), audioSource, "Play") as UnityAction;
    UnityEventTools.AddPersistentListener (script.Events, methodDelegate);

    // animator.Play(string) - its only add this animator
    script.Events = new UnityEvent();
    UnityAction<string> methodDelegateString = System.Delegate.CreateDelegate(typeof(UnityAction<string>), Selection.activeGameObject.GetComponent<Animator>(), "Play") as UnityAction<string>;
    UnityEventTools.AddStringPersistentListener(script.Events, methodDelegateString, "lala");

    Undo.RegisterCreatedObjectUndo(go, "Create " + go.name);
    Selection.activeObject = go;
}

我相信unityevent的第一个元素是覆盖,因为如果我评论为动画师添加持久监听器,音频播放将起作用。

enter image description here

1 个答案:

答案 0 :(得分:3)

    // audioSource.Play
    script.Events = new UnityEvent();
    UnityAction methodDelegate = System.Delegate.CreateDelegate (typeof(UnityAction), audioSource, "Play") as UnityAction;
    UnityEventTools.AddPersistentListener (script.Events, methodDelegate);

    // animator.Play(string) - its only add this animator
    script.Events = new UnityEvent();
    UnityAction<string> methodDelegateString = System.Delegate.CreateDelegate(typeof(UnityAction<string>), Selection.activeGameObject.GetComponent<Animator>(), "Play") as UnityAction<string>;
    UnityEventTools.AddStringPersistentListener(script.Events, methodDelegateString, "lala");

我猜测这是个问题:

 script.Events = new UnityEvent();

您正在执行此操作两次 - 一次在开始时,然后在您向Events对象添加事件侦听器后,您再次调用上述代码。

上面的代码将使用没有任何附加事件处理程序的全新UnityEvent()对象实例替换原始实例。然后,您将一个事件处理程序附加到它 - 因此只有一个工作原因。

请改为尝试:

    script.Events = new UnityEvent(); // Only create the UnityEvent instance once
    UnityAction methodDelegate = System.Delegate.CreateDelegate (typeof(UnityAction), audioSource, "Play") as UnityAction;
    UnityEventTools.AddPersistentListener (script.Events, methodDelegate);

    UnityAction<string> methodDelegateString = System.Delegate.CreateDelegate(typeof(UnityAction<string>), Selection.activeGameObject.GetComponent<Animator>(), "Play") as UnityAction<string>;
    UnityEventTools.AddStringPersistentListener(script.Events, methodDelegateString, "lala");

Dislcaimer:我之前从未使用过Unity - 可能有另一种方法可以向脚本添加多个事件处理程序。