- Home /
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!
Answer by Krishx007 · Mar 31, 2021 at 04:12 PM
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);
}
What I usually do is i clear the event before assigning the new one instead of checking for the existing.
e.g in your case I will do this:
unityEvent=new UnityEvent(); unityEvent.AddListener(unityAction);
or we can use:
unityEvent.RemoveAllListeners();
Your answer
Follow this Question
Related Questions
GameObject.Find breaks code with UnityEvent 2 Answers
How do i declare an event listener? 2 Answers
Event Listener for Javascript? 0 Answers
Passing sender object as an argument in AddListener method 1 Answer
Assigning events on runtime 0 Answers