Skip to content

Instantly share code, notes, and snippets.

@marcotmp
Last active August 3, 2021 21:07
Show Gist options
  • Select an option

  • Save marcotmp/b60fbb5c908f654f90d91c13b1158ada to your computer and use it in GitHub Desktop.

Select an option

Save marcotmp/b60fbb5c908f654f90d91c13b1158ada to your computer and use it in GitHub Desktop.
Handle listeners for multiple buttons in Unity
[SerializeField] private Button[] buttons;
private ListenerHandler[] listeners;
public class ListenerHandler
{
public int id;
public void Call() => onCall?.Invoke(id);
public Action<int> onCall;
}
private void AddListeners()
{
listeners = new ListenerHandler[buttons.Length];
for (int i = 0; i < buttons.Length; i++)
{
listeners[i] = new ListenerHandler
{
id = i,
onCall = OnButtonPress
};
buttons[i].onClick.AddListener(listeners[i].Call);
}
}
private void RemoveListeners()
{
for (int i = 0; i < buttons.Length; i++)
{
buttons[i].onClick.RemoveListener(listeners[i].Call);
}
}
private void OnButtonPress(int index)
{
Debug.Log($"Button {index} pressed");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment