Randomly select from array.

Hello Unity euthusiasts!

I have searched around UA, but I have not optained a answer. I would like to know how to select a random object, let us say Transforms in a array for later use.

I could imagine using Random.Range, MABYE like so:

var transforms : Transform[];

function Update ()
// use Random.Range here? 

But I do not know how to randomly select the Transform.

transforms[Random.Range(0, transforms.Length)];

Arrays indices start at zero, and go to Length-1. When you use Random.Range with integers, the first value may be selected, but only values less than the second may be, so that's the one to use. The function seems to have been designed specifically with this kind of selection from an array in mind.

You didn't search very well..


var randomNumber : int = Random.Range(0,transform.length);

var randomTransform = transforms[randomNumber];

Declare the random number before using it, so you can make sure it's an integer, because Random.Range can else produce a float.