Skip to content

Instantly share code, notes, and snippets.

@marcotmp
Last active August 3, 2021 21:07
Show Gist options
  • Save marcotmp/b60fbb5c908f654f90d91c13b1158ada to your computer and use it in GitHub Desktop.
Save marcotmp/b60fbb5c908f654f90d91c13b1158ada to your computer and use it in GitHub Desktop.

Revisions

  1. marcotmp revised this gist Aug 3, 2021. 1 changed file with 5 additions and 0 deletions.
    5 changes: 5 additions & 0 deletions HandleMultipleButtonsListeners.cs
    Original file line number Diff line number Diff line change
    @@ -30,3 +30,8 @@ private void RemoveListeners()
    buttons[i].onClick.RemoveListener(listeners[i].Call);
    }
    }

    private void OnButtonPress(int index)
    {
    Debug.Log($"Button {index} pressed");
    }
  2. marcotmp revised this gist Aug 3, 2021. 1 changed file with 3 additions and 0 deletions.
    3 changes: 3 additions & 0 deletions HandleMultipleButtonsListeners.cs
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,6 @@
    [SerializeField] private Button[] buttons;
    private ListenerHandler[] listeners;

    public class ListenerHandler
    {
    public int id;
  3. marcotmp created this gist Aug 3, 2021.
    29 changes: 29 additions & 0 deletions HandleMultipleButtonsListeners.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,29 @@
    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);
    }
    }