GridLayout dynamic elements, with button onclick

I have a grid layout, populated dynamically, i use a prefab that i add to the script and i insantiate it, everything works expect when i click on the button, the function is called but with the wrond i, i read on the internet that using a tmp variable will correct this problem but for me it’s not, it’s a random value that is passed to function
why is that ?

here is my code please help

    void populate()
    {
        int nbElements = SetLevelScript.levelsOrder.Length;
        int i = 0;
        foreach (int level in SetLevelScript.levelsOrder)
        {
            createPrefab(i);
            i++;
        }
       }
     void createPrefab(int i) {



        int copy = i;

        GameObject newObject = (GameObject)Instantiate(prefabLevel, transform);

        newObject.transform.SetParent(this.gameObject.transform, false);
        newObject.transform.localScale = Vector3.one;



        Transform image = newObject.transform.GetChild(0);
        newObject.transform.GetChild(1).GetComponent<Button>().name = "" + copy;

        GameObject number = image.transform.Find("number").gameObject;

        TextMeshProUGUI txt = number.GetComponent<TextMeshProUGUI>();
        txt.text = "" + (copy + 1);
     
        newObject.transform.GetChild(1).GetComponent<Button>().onClick.AddListener(() =>
        {

            int tmp = i;
            clickStage(tmp);
        });     

    }


       void  clickStage(int stage)
       {
           Debug.Log("bouton  ===" + stage);
       }

Here is my unity

@doliprane

Use code tags when posting code… it is really hard to read code without proper formatting.

You can edit your post.

1 Like

Thank you, i just edit my post