S
S
Sergey Serega2019-08-31 20:03:22
Unity
Sergey Serega, 2019-08-31 20:03:22

How to programmatically add events to buttons in unity?

Why, when trying to write like this, debug.log displays the last i of the cycle (and it should output 0,1,2....):

//цикл...
go.transform.Find("btn1").GetComponent<Button>().onClick.AddListener(
                    delegate 
                    {
                        Debug.Log( i );
                    }
);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Gaydak, 2019-08-31
@SirSerega

Try this) should understand that a separate instance of a variable, and not a variable from a loop.
in fact, it simply referred to the cycle variable (area in memory), but the fact that it changes - the delegate did not care.

int currentNum = i;
....
delegate 
                    {

                        Debug.Log(currentNum  );
                    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question