Search Unity

Randomize Array in C#

Discussion in 'Scripting' started by WolfShield, Apr 24, 2011.

Thread Status:
Not open for further replies.
  1. WolfShield

    WolfShield

    Joined:
    Feb 7, 2011
    Posts:
    126
    Hello again,
    I know how to program in C#, but Unity doesn't support all of the things C# normally can do.

    Anyway, what I need now is an array that has twelve(12) string values put in a random order.
    Thanks in advance,

    - WolfShield
     
  2. increpare

    increpare

    Joined:
    Nov 17, 2010
    Posts:
    151
  3. TheRaider

    TheRaider

    Joined:
    Dec 5, 2010
    Posts:
    2,250
    just curious

    why not just randomise the int you use to access the array?
     
    khaled24 and longbowgr like this.
  4. increpare

    increpare

    Joined:
    Nov 17, 2010
    Posts:
    151
    Can't speak for WS, but:

    Sometimes you want to be able to iterate through them all in a random order without going over duplicates
    Sometimes you want to preserve the random order (to go through in the same order several times, or on several different occasions)
    For clarity: sometimes you just feeling like saying "shuffle this array", and the most meaningful way to express this is ar.shuffle() :)

    [ I pick random elements a lot as well, I think clearer to add a PickRandom extension method than to do it every time with random()s (every time it comes up, I have to double check that I'm not missing out the last element :p ) , but each to their own ]
     
    Psyco92, anattress and N00bKefka like this.
  5. WolfShield

    WolfShield

    Joined:
    Feb 7, 2011
    Posts:
    126
    Thanks for the help guys!

    - WolfShield
     
  6. HarvesteR

    HarvesteR

    Joined:
    May 22, 2009
    Posts:
    531
    If you want to shuffle the array (randomize the order of the elements), you can try the Knuth shuffle algorithm:

    Code (csharp):
    1.  
    2. void reshuffle(string[] texts)
    3.     {
    4.         // Knuth shuffle algorithm :: courtesy of Wikipedia :)
    5.         for (int t = 0; t < texts.Length; t++ )
    6.         {
    7.             string tmp = texts[t];
    8.             int r = Random.Range(t, texts.Length);
    9.             texts[t] = texts[r];
    10.             texts[r] = tmp;
    11.         }
    12.     }
    13.  
     
    Jmonroe, SP5068, Eloren and 28 others like this.
  7. IINVENCIBLE

    IINVENCIBLE

    Joined:
    Feb 11, 2021
    Posts:
    3

    work perfectly for me, thanks a lot!!
     
  8. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,420
    Please use the like button instead as a way to say thanks. The above is necroing a post from nearly 12 years ago.
     
Thread Status:
Not open for further replies.