list.add gameobject isnt adding to list

with a little bit of debugging i was able to find out what was happening but i’m not sure how to fix it. basically it isn’t adding to the list more than once. “cardList.Count” is always returning 1, even for the second loop cycle, then it breaks and doesn’t loop again. i looked it up a couple of times and every solution i find tell me that this should work.

for (int i = 0; i < 3; i++)
                {
                    cardList = new List<GameObject>();
                    print("adding");
                    cardList.Add((GameObject)Instantiate(cardPrefab, new Vector3(1000, 100, 0), Quaternion.identity));
                    print("Added " + cardList.Count + " Cards");
    
                    GameObject cardToAdd = cardList*;* 

//ArgumentOutOfRangeException: Index was out of range
//Must be non-negative and less than the size of the collection.

cardToAdd.transform.SetParent(this.gameObject.transform);
Cards c = cardToAdd.GetComponent();
c.Attack = true;
c.name = “Attack”;
c.Value = 3;

}

You’re recreating the list with every iteration of the loop :frowning: Move the first line to outside of the loop. You should also instantiate the prefab and then add it… something like:

cardList = new List<GameObject>();

for (int i = 0; i < 3; i++)
{
    print("adding");

    GameObject cardToAdd = Instantiate(cardPrefab, new Vector3(1000, 100, 0), Quaternion.identity)) as GameObject;

    cardToAdd.transform.SetParent(this.gameObject.transform);

    Cards cards = cardToAdd.GetComponent<Cards>();
    cards.Attack = true;
    cards.name = "Attack";
    cards.Value = 3;

    cardList.Add(cardToAdd);
}