Spawning all objects in an array at once to position.

Curious, using the below code which works spawning a random playing card using a button:
(Credit to Jay Jennings and his youtube video which has helped me learn Unity 2D: Many Game Objects from a Prefab & Array of Sprites - YouTube )

My question, and I have been trying so many times to alter this code, is right now when I press the game button, playing cards are spawning in random order (I have all the card sprites, 52 in an array which is called for by a card prefab), and this works perfect, How can I spawn all cards but not randomly, because random produces duplicate cards, so all 52 cards laid out. I would think the code would need to be in the Start function. It appears I could just change/alter the underlined first line and that would be it, but Random.Range is stumping me, also is there a Fixed.Range or just Range?

Thanks so much for looking into at this post.

{
public GameObject cardPrefab;
public Sprite[ ] cardSprites;
public void MakeRandomCard()
{
int arrayIdx = Random.Range(0, cardSprites.Length);
Sprite cardSprite = cardSprites[arrayIdx];
string cardName = cardSprite.name;
GameObject newCard = Instantiate(cardPrefab);
newCard.name = cardName;
newCard.GetComponent().cardName = cardName;
newCard.GetComponent().sprite = cardSprite;
}

Random.Range(lower, upper) simply returns a random value between lower and upper.
If you want to get rid of duplicates (while still spawning in a random order), what you can do is:

  • Create a List and add all cards
  • Randomize the order of the items in the list
  • Spawn everything in the list in the order it is in now.
List<Card> cards = new List<Card>();
cards.AddRange(CARDS);
cards = cards.OrderBy(a => Guid.NewGuid()).ToList(); // Quick & dirty Randomization

for (int i = 0; i < cards.Count; i++)
    SpawnCard(cards[i]);

Thank you for this, I will try when I get home, and try and understand it too.

Appreciate it!