Check if a listener has already been added to a button?

I’ve run into a bit of a snag with creating a button in the editor.

I need to dynamically add listeners to my button, but it just keeps adding the same 3 listeners over and over because there is nothing stopping it from adding the same ones on each Awake.

Here is my code…

		var button = gameObject.GetComponent<Button>();
			
		if (receiver1 != null)
		{
		    var go1 = receiver1;
            UnityAction<GameObject> action1 = new UnityAction<GameObject>(this.OnClickEvent1);
	     	UnityEventTools.AddObjectPersistentListener<GameObject>(button.onClick, action1, go1);            
		}
			
		if (receiver2 != null)
		{
			var go2 = receiver2;
            UnityAction<GameObject> action2 = new UnityAction<GameObject>(this.OnClickEvent2);
     		UnityEventTools.AddObjectPersistentListener<GameObject>(button.onClick, action2, go2);        	
		}
			
		if (receiver3 != null)
		{
			var go3 = receiver3;
            UnityAction<GameObject> action3 = new UnityAction<GameObject>(this.OnClickEvent3);
     		UnityEventTools.AddObjectPersistentListener<GameObject>(button.onClick, action3, go3);       	
		}

Any help is appreciated!

2 Answers

2

Define your button, action1, action2 and action3 globally and move all of your add listener methods inside OnEnable() method (instead of Awake). And then add these lines to your script :

void OnDisable(){
    UnityEventTools.RemovePersistentListener(button.onClick, action1);
    UnityEventTools.RemovePersistentListener(button.onClick, action2);
    UnityEventTools.RemovePersistentListener(button.onClick, action3);
}

Now your listeners will be removed every time your scripts done playing!

Thank you very much! :)

this code with give u the number of listerners added

Button btn;
Debug.log(btn.onClick.GetPersistentEventCount());