Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question Spawning all objects in an array at once to position.

Discussion in 'Scripting' started by gregnice, Jan 23, 2023.

  1. gregnice

    gregnice

    Joined:
    Dec 8, 2022
    Posts:
    2
    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<Card>().cardName = cardName;
    newCard.GetComponent<SpriteRenderer>().sprite = cardSprite;
    }
     
  2. SF_FrankvHoof

    SF_FrankvHoof

    Joined:
    Apr 1, 2022
    Posts:
    780
    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.

    Code (CSharp):
    1. List<Card> cards = new List<Card>();
    2. cards.AddRange(CARDS);
    3. cards = cards.OrderBy(a => Guid.NewGuid()).ToList(); // Quick & dirty Randomization
    4.  
    5. for (int i = 0; i < cards.Count; i++)
    6.     SpawnCard(cards[i]);
     
  3. gregnice

    gregnice

    Joined:
    Dec 8, 2022
    Posts:
    2
    Thank you for this, I will try when I get home, and try and understand it too.

    Appreciate it!