Unity中按钮OnClick事件异常:所有按钮绑定相同参数问题
循环绑定Unity按钮OnClick时参数一致的问题解决
这是闭包捕获变量引用导致的经典问题:你在循环里用delegate绑定i时,闭包并没有捕获当前循环的i数值,而是抓了i这个变量本身的引用。等循环跑完,i的值已经变成了buttonsParent.childCount(也就是你看到的2),所以所有按钮点击时都会用这个最终值调用setId。
解决方案
在循环内部新建一个局部变量,把当前的i值存进去,让闭包捕获这个局部变量——因为每次循环的局部变量都是全新的,每个按钮的闭包就会绑定各自对应的数值。同时建议缓存Button组件,避免重复查找:
[SerializeField] private Transform buttonsParent; private void genButtons() { for (int i = 0; i < buttonsParent.childCount; i++) { // 用局部变量保存当前循环的i值 int currentId = i; Button targetBtn = buttonsParent.GetChild(i).GetComponent<Button>(); targetBtn.onClick.RemoveAllListeners(); targetBtn.onClick.AddListener(delegate { itemPlacer.setId(currentId); }); } }
也可以用Lambda表达式简化写法,效果完全一样:
[SerializeField] private Transform buttonsParent; private void genButtons() { for (int i = 0; i < buttonsParent.childCount; i++) { int currentId = i; Button targetBtn = buttonsParent.GetChild(i).GetComponent<Button>(); targetBtn.onClick.RemoveAllListeners(); targetBtn.onClick.AddListener(() => itemPlacer.setId(currentId)); } }
内容的提问来源于stack exchange,提问作者CrisDev
相关产品推荐
相关产品推荐

