UGUI
UIBUTTON: UGUI按钮父物体
void Start() {
for (int i = 0; i < UIBUTTON.childCount; i++) {
//此行代码会带来闭包陷阱
//UIBUTTON.GetChild(i).GetComponent<Button>().onClick.AddListener(delegate() { UGUIbuttonClcikAction(UIBUTTON.GetChild(i).name); });
//解决闭包陷阱 int temp = i; UIBUTTON.GetChild(i).GetComponent<Button>().onClick.AddListener(delegate() { UGUIbuttonClcikAction(UIBUTTON.GetChild(temp).name); }); }
}
private void UGUIbuttonClcikAction(string num)
{ print(num); }
NGUI
NGUIBUTTON:NGUI按钮父物体
void Start() {
for (int i = 0; i < NGUIBUTTON.childCount; i++) {
UIButton nguibutton = NGUIBUTTON.GetChild(i).GetComponent<UIButton>();
//此行代码会带来闭包陷阱
//EventDelegate.Add(nguibutton.onClick, delegate() { NGUIbuttonClcikAction(NGUIBUTTON.GetChild(i).name); });
//解决闭包陷阱
int temp = i; EventDelegate.Add(nguibutton.onClick, delegate() { NGUIbuttonClcikAction(NGUIBUTTON.GetChild(temp).name); }); }
}
private void NGUIbuttonClcikAction(string buttonName) { print(buttonName); }