Skip to content

Instantly share code, notes, and snippets.

@rutcreate
Last active March 11, 2024 00:02
Show Gist options
  • Select an option

  • Save rutcreate/3e6ae2f39cbe2a41d84a to your computer and use it in GitHub Desktop.

Select an option

Save rutcreate/3e6ae2f39cbe2a41d84a to your computer and use it in GitHub Desktop.
Unity3D: Best way to add listener programmatically for Button onClick
using UnityEngine;
public class MyButton {
public Button[] buttons;
private void Start() {
for (int i = 0; i < buttons.Length; i++) {
Button button = buttons[i];
var index = i;
button.onClick.RemoveAllListeners();
button.onClick.AddListener(() => OnClick(index));
}
}
private void OnClick(int index) {
Debug.Log("You click button at index: " + index);
}
}
@DavemourDev

Copy link
Copy Markdown

I was trying to do this for an hour and the solutions I found before this were innecessary complex. Thank you! This worked fine for me!

@yusuferol175

yusuferol175 commented Jun 11, 2023

Copy link
Copy Markdown

that' s so useful ๐Ÿ‘

@3Samourai

Copy link
Copy Markdown

Thanks :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment