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

How to get 4 random numbers in a row, without them being the same.

Discussion in 'Scripting' started by vemmu, Jun 11, 2022.

  1. vemmu

    vemmu

    Joined:
    May 15, 2022
    Posts:
    8
    I have a quiz game and i need to randomize the button texts, i need some kind of way get 4 numbers between 0 and 3 in randomized order.
    LippuScript.Lista is a list from other script witch has 3 random answers and one correct answer.
    The problem i am having is that the correct answer is always at the same spot.
    Code (CSharp):
    1.  
    2.        
    3.         randomilistasta = lippuScript.Lista[0];
    4.         randomilistasta2 = lippuScript.Lista[1];
    5.         randomilistasta3 = lippuScript.Lista[2];
    6.         randomilistastaVika = lippuScript.Lista[3];
    7.  
    8.         Button1.text = randomilistasta;
    9.         Button2.text = randomilistasta2;
    10.         Button3.text = randomilistasta3;
    11.         Button4.text = randomilistastaVika;
     
  2. iMobCoding

    iMobCoding

    Joined:
    Feb 13, 2017
    Posts:
    161
    There are many many ways to shuffle a list in c#. As you have only 4 items and performance/garbage isn't an issue, try with Linq:

    Code (CSharp):
    1. using System.Linq;
    2.  
    3. void SomeMethod()
    4. {
    5.     var shuffledList = lippuScript.Lista.OrderBy(a => System.Guid.NewGuid()).ToList();
    6.  
    7.     Button1.text = shuffledList[0];
    8.     Button2.text = shuffledList[1];
    9.     Button3.text = shuffledList[2];
    10.     Button4.text = shuffledList[3];
    11. }
    Of course, be sure that your list has those 4 items or you'll get exceptions
     
    Last edited: Jun 11, 2022
  3. vemmu

    vemmu

    Joined:
    May 15, 2022
    Posts:
    8
    Thank you very much!
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,951