Search code examples
c#unity-game-engineinstantiationgameobject

Grid Layout add Gameobject with Instantiate previous object not from above


Here I created an Instantiate function using a click button to create a GameObject from the parent object Layout Grid, it worked fine

But there's a problem, when i click the button it's initially on top but when i click more than 3 times the previous GameObject is on the bottom not on the top and not in order, and that's my problem i want the previous GameObject to be on top and in the order when i click the button

    public GameObject exampleParent, exampleChild;

    public void gItem(int i)
    {
        Instantiate(exampleChild, exampleParent.transform);
        exampleChild.transform.SetAsFirstSibling();
        exampleChild.gameObject.transform.Find("Text").GetComponent<TMP_Text>().text = Items[i].gameObject.GetComponent<AddItemC>().textPopup;
    }

This is a video of the problem I'm having, GameObject should be on top and sorted from the moment I click the button, but previous GameObject are on the bottom :

https://drive.google.com/file/d/1VKpvuZ5U_o0oVdOmcWIi_A9Qf8LwpCOD/view

And this is the Grid Layout Group I'm using:

enter image description here


Solution

  • I have changed to this and it works

        public void gItem(int i)
        {
            GameObject obs = Instantiate(exampleChild, exampleParent.transform) as GameObject;
            obs.transform.Find("Text").GetComponent<TMP_Text>().text = Items[i].gameObject.GetComponent<AddItemC>().textPopup;().AddItemToPlayer();
        }