Skip to content

Instantly share code, notes, and snippets.

@ksnnacar
Created November 28, 2017 21:42
Show Gist options
  • Save ksnnacar/257e329728532e1d9574b4de6f3a9b0b to your computer and use it in GitHub Desktop.
Save ksnnacar/257e329728532e1d9574b4de6f3a9b0b to your computer and use it in GitHub Desktop.
AddRemovePersistentListener.cs
using UnityEngine.UI;
using UnityEditor.Events;
using UnityEngine.Events;
public class AddRemovePersistentListener : MonoBehaviour
{
/*
Just a basic use case for removing and adding listeners on runtime.
Sometimes it's pretty handy.
It may be expensive for dealing with a bunch of buttons and listeners. Use at your own risk.
K.S.A. 29.11.17
github.com/ksnnacar
*/
public SomeScript someScript;
public Button someButton;
void Start ()
{
UnityAction<int> intAction = (x) => { someScript.intMethod(x); };
int a = someButton.onClick.GetPersistentEventCount();
//Iterate over existing event listeners;
for (int i = 0; i < a; i++)
{
UnityEventTools.RemovePersistentListener(someButton.onClick, 0);
}
UnityEventTools.AddIntPersistentListener(someButton.onClick, intAction, 1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment