Some unknow mistake

when i Instantiate some gameobject with button component ,i want to those button run function(with value) when i click,But even though every function show an impossible number ------temp+1

void Start()
{
    int temp = Random.Range(5, 10);
    for (int i = 0; i < temp; i++)
    {
        GameObject temp2 = Instantiate(card);
        temp2.transform.Find("Canvas/button").GetComponent<Button>().onClick.AddListener( ()=> chosecard(i));
        temp2.transform.Find("Canvas/text").GetComponent<Text>().text = (i+1).ToString();
        temp2.transform.position = new Vector2(startpos.position.x + 13f/(temp-1)*i, -4f);
        cards.Add(temp2);   
    }
}

line 8 ,every chosecard showed temp+1

–

2 Answers

2

The closure you create as argument of AddListener captures i as variable. Since onClick is invoked after the loop has finished, it will see the final value of i after the loop has finished. To fix this, declare a new local variable in the loop body and copy i to it. Like this:

int index = i;
temp2.transform.Find("Canvas/button").GetComponent<Button>().onClick.AddListener( ()=> chosecard(index));

I’d like to thank…

–

it is knowledge about closur,i clear it