Search Unity

How to get a random from an array????

Discussion in 'Scripting' started by balu89, Apr 30, 2008.

  1. balu89

    balu89

    Joined:
    Apr 15, 2008
    Posts:
    30
    Hi all,

    I have an array, and I need to get a random index from it. The random method from javascript does not work in Unity, so what can I use instead??

    Thank you... 8)
     
  2. bronxbomber92

    bronxbomber92

    Joined:
    Nov 11, 2006
    Posts:
    888
    Something like...
    Code (csharp):
    1. var randIndex : int = Mathf.RoundToInt(Random.Range(0, maxIndex));
     
  3. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    You don't need RoundToInt; Random.Range does integers by itself.

    Code (csharp):
    1. var randIndex = Random.Range(0, maxIndex);
    (Assuming maxIndex is an int.)

    --Eric
     
  4. AaronC

    AaronC

    Joined:
    Mar 6, 2006
    Posts:
    3,552
    If you were instantiating a random prefab from a list of prefabs assigned in the inspector, is this the method you'd use?

    Always wondered about this.

    AC
     
  5. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    Yep.

    Code (csharp):
    1. var somePrefabs : GameObject[];
    2.  
    3. function Start () {
    4.    Instantiate(somePrefabs[Random.Range(0, somePrefabs.Length)]);
    5. }
    --Eric
     
  6. AaronC

    AaronC

    Joined:
    Mar 6, 2006
    Posts:
    3,552
    Thanks Eric thats totally cool 8)

    AaronC