Copy object in list multiple times

Hello Unity Community,

I’m learning slowly to write codes and I found myself with what I think is a hardy thing to do (or at least nothing came up from my goolge research.)

Let’s say I have a list of 5 GameObjects. Is there a way to indicate Unity to duplicate one of the GameObjects alredy in the list and add them all to the list. So for example the list will end with a length of 50, but 10 of each listed objects in the begining.

public List<GameObject> cards;
	
	public int Card1Start = 20;
	public int Card2Start = 16;
	public int Card3Start = 12;
	public int Card4Start = 8;
	public int Card5Start = 4;

Idealy I would like to be able to specify how many times I want that item to be repeated in the list.

Thanks to anyone who can answer me this.

Very simple :slight_smile:

public int[] CardStart = { 20,16,12,8,4 };

public void createDeck()
{
     for( int a = 0; a < 5; a++ )
     {
         for (int i = 0; i < CardStart[a] - 1; i++) 
         {
             cards.Add(cards[a]);
         }
     }
}

Basicly you are on the right track. To make things easier, I would create a specific method which handles creating any number of GameObjects to your list of gameobjects:

void AddMultipleGameObjects(GameObject objectToAdd, int count numberToAdd, 
   List<GameObject> targetList)
{
    for(int i=0;i<count;i++)
    {
        targetList.Add(objectToAdd);
    }
}

Then in createdeck method just call:

AddMultipleGameObjects(cards[0],Card1Start, cards);

as many time you need