Skip to content

Instantly share code, notes, and snippets.

@rutcreate
Last active March 11, 2024 00:02
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rutcreate/3e6ae2f39cbe2a41d84a to your computer and use it in GitHub Desktop.
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);
}
}
@avodhel
Copy link

avodhel commented Jan 29, 2022

should be like:

var i2 = i;
button.onClick.AddListener(() => OnClick(i2));

source: https://docs.microsoft.com/tr-tr/archive/blogs/ericlippert/closing-over-the-loop-variable-considered-harmful

@keremkrz
Copy link

Thank you very mucjh öperi,m geri kaç

@DavemourDev
Copy link

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
Copy link

yusuferol175 commented Jun 11, 2023

that' s so useful 👍

@3Samourai
Copy link

Thanks :)

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