- Home /
[C#] UI Button AddListener issue with an array
Hello In this code below i'm trying to send the position of my slot as an integer, but no matter what, it's alway send the lenght of the array (3) on the log.
void Start()
{
prefab = (Button)Resources.Load("btn_newChar", typeof(Button));
clone = new Button[3];
con = new mysql_conn();
con.Conectar();
rs = con.Exec("SELECT cod_MenuChar, slot1, slot2, slot3 from MenuChar where cod_user ="+ Global.cod_usuario);
if (rs.Read())
{
Global.cod_MenuChar = (int)rs["cod_MenuChar"];
for(int i = 0; i < clone.Length; i++)
{
if(!(bool)rs["slot"+(i+1)])
{
clone[i] = Instantiate(prefab, transform.position + new Vector3(70,20-(15*i),0), transform.rotation) as Button;
clone[i].transform.SetParent(transform, true);
//
clone[i].onClick.AddListener(() => SlotPressionado(i));
//
clone[i].transform.localScale = new Vector3(1, 1, 1);
t = clone[i].GetComponentsInChildren<Text>();
foreach (Text a in t)
{
if(a.name == "slot")
{
a.text = "Slot 0"+(i+1);
}
}
}
}
}
}
public void SlotPressionado(int i)
{
Debug.Log(i);
}
Answer by hhernanni · Mar 29, 2015 at 03:01 PM
You should disconnect the memory address from i. Your method, SlotPressionado(), always will get the last value put into the i address. A easy approach would be create a new variable inside your loop and pass i to it. You could clone as well. for(int i = 0; i < clone.Length; i++) { int item = i; // rest of your code, but where you see i you replace for item. }
I hope I could help.
Your answer
Follow this Question
Related Questions
Scripting button functionality inside class with created object's method 1 Answer
Unity - keep created buttons after quit 1 Answer
Missing function in button on click 1 Answer
Script Two Button Functions At Once 1 Answer
Transferring Windows Forms buttons and labels to Unity UI (Beginner Level) 0 Answers