[SOLVED] Adding Gameobject to a list overwrites everything

I’m instantiating multiple instances of a prefab that has a “Hut” script attached to it. The Hut script has a public int called TESTID.

public class test : MonoBehaviour {

    public GameObject Hutprefab;

    private int tstID = 0;

    public List<GameObject> hutList = new List<GameObject>();

    public void CreateHut()
    {
       
        GameObject newhut = Hutprefab;

        Instantiate (newhut, transform.position, Quaternion.identity);
        hutList.Add (newhut);
        newhut.GetComponent<Hut> ().TESTID = tstID;
        tstID++;
       

    }
}

The instantiating works fine, each new gameobject has a new TESTID. But when I try to add them to a list, the list grows by one but also overwrites every item in the list with the newest one.

Instatiate return a new GameObject based on the one you passed. So you need to do:

1 Like

You’re not assigning your Instantiate GameObject to your newHut variable, you are assigning the prefab.

GameObject newhut = Instantiate(Hutprefab, transform.position, Quaternion.identity);
hutList.Add(newhut);
1 Like

Thanks for the super fast answers. Everything works now!

you should add it to the list after changing the ID, also the instantiate statement needs to be changed.

public void CreateHut()
    {
        GameObject newhut;
        newhut = Instantiate (Hutprefab, transform.position, Quaternion.identity);
        newhut.GetComponent<Hut> ().TESTID = tstID;
        hutList.Add (newhut);
        tstID++;
    }