Search Unity

UnityEvent and existing listeners

Discussion in 'Scripting' started by angrypenguin, Jul 27, 2015.

  1. angrypenguin

    angrypenguin

    Joined:
    Dec 29, 2011
    Posts:
    15,619
    Is there any way to see if a UnityEvent already has a given listener?

    I'm writing some auto-hookup code for stuff that can be created either at runtime or in the Editor. For stuff that's created in the Editor it's entirely possible that they'll also hook up the events, and I don't want them getting called twice. (I also don't want to have to write a bunch of instructions about when not to hook up events.)

    Alternatively, it'd be nice to know more details about AddListener and RemoveListener. Will AddListener add duplicates? Will RemoveListener throw an exception if I remove something that's not there? The docs don't go into any such details.
     
  2. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
  3. angrypenguin

    angrypenguin

    Joined:
    Dec 29, 2011
    Posts:
    15,619
    Yeah, I came to the same conclusion. It'd be nice if the docs were more specific about what happens if you add a listener multiple times or remove one that's not there. I could test those cases for myself, but I'm always wary of relying on undocumented features.
     
  4. DonLoquacious

    DonLoquacious

    Joined:
    Feb 24, 2013
    Posts:
    1,667
    I would imagine that the list of listeners isn't "unique-only" and that removing a listener that isn't there would do absolutely nothing- I also imagine that neither throw warnings or errors or anything. I agree though- relying on something undocumented, even if it follows the normal trend of such things, may cause problems down the line.

    I'm currently having a similar annoyance with the internal ReorderableList class in UnityEditorInternal...
     
  5. Krishx007

    Krishx007

    Joined:
    Jul 15, 2014
    Posts:
    14
    I implemented this extension method but i guess it will work at runtime . Could anyone help? https://answers.unity.com/questions...om-being-added-twice.html?childToView=1826133

    public static void AddListenerOnce(this UnityEvent unityEvent, UnityAction unityAction)
    {
    for (int index = 0; index < unityEvent.GetPersistentEventCount(); index++)
    {
    Object curEventObj = unityEvent.GetPersistentTarget(index);
    string curEventName = unityEvent.GetPersistentMethodName(index);
    Debug.Log("curEventName: " + curEventName + ", unityAction: " + unityAction.Method.Name);
    if ((Object)unityAction.Target == curEventObj)
    {
    Debug.LogError("Event is already added: " + curEventName);
    return;
    }
    }
    unityEvent.AddListener(unityAction);
    }