UnityEvent prevent listener from being added twice

I’m looking for a way to prevent a listener method being added twice to a Button onClick event.

Can I just check in the list of listeners, if it already exists and only add it if it doesn’t or is there some other elegant way to prevent the same method being added multiple times?

I’d like this as a safety measure against designers who might add button clicked listeners through the inspector, although they are already set in code or vice versa.

Thanks!

I implemented this extension method but it’s not working currectly. Could anyone help?

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

I realize this question is pretty old, but it comes up on top of the google search results and there is a pretty easy fix: You can simply first remove the event you’re about to add (if it hasn’t been added before, nothing happens, if one or more instances have already been added they will be removed. Even better, you could make an Extension method like so:

public static class ButtonExtensions {
     public static void AddListenerOnce(this Button.ButtonClickedEvent buttonClickedEvent, 
             UnityEngine.Events.UnityAction action) {
         buttonClickedEvent.RemoveListener(action);
         buttonClickedEvent.AddListener(action);
     }
}

and then you’ll be able to call it just like the regular AddListener:

// regular AddListener call
button.onClick.AddListener(MyAction);
    
// our new extension method which makes sure the action is added only once
button.onClick.AddListenerOnce(MyAction);