Question by
hghammoud · Jan 24, 2017 at 01:47 AM ·
scripting problembuttonsfor-loopdynamicallylisteners
Adding listeners buttons in for loop
Hello, I tried every solution on the web. I can't get this to work.
I tried
Capturing variable locally
Externalizing the for loop into a different function
passing string, objects or int
not using lambda and calling a function the UpgradeWidgetController.selectUpdate()
Only the last dynamically created button/UpgradeWidgetController answers to the onClick event
Graphically everything is rendering properly with the right text, colors and position.
Can someone pls help and tell me that is wrong with my code?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UpgradesController : MonoBehaviour {
public Technology _technology;
public void Start(){
List<GameObject> children = new List<GameObject>();
foreach (Transform child in transform) children.Add(child.gameObject);
children.ForEach(child => Destroy(child));
inject ();
}
public void inject(){
for (int i = 0; i <= _technology._maxLevel; i++) {
int _index = i;
TechnologyUpgrade _upgrade = TechnologyUpgrade.GetByType(_technology, _index);
GameObject go = Resources.Load<GameObject> ("Prefab/UpgradeWidget");
go = (GameObject)Instantiate (go);
UpgradeWidgetController uw = go.GetComponent<UpgradeWidgetController> ();
uw._technologyupgrade = _upgrade;
go.transform.SetParent(gameObject.transform);
go.transform.localScale = new Vector3 (1, 1, 1);
go.transform.localPosition = new Vector3 (0, i * (-195), 0);
Button _button = go.GetComponentInChildren<Button> ();
_button.onClick.AddListener (() => {clicked(_index);});
}
}
public void clicked(int _name){
Debug.Log (_name);
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612105448im_/https://answers.unity.com/themes/thub/images/avi.jpg)