picking a random object from an array

I have made an array with 3 objects in them. On start two of them are in place and the third is off screen. I have them moving screen left and after they get to a certain point in world space I move them down. What I want to do is randomly pick one of the three object from my array and set it to a set position and start moving it. My sticky point is selecting the object randomly. ANy thoughts?

Thanks in advance!

Welcome to the forums! :slight_smile:

Use Random.Range to get a random index in your array and away you go.

Yeah. I was thinking that. Though, I’m not quite sure how to link that with the elements in the array.

The other thing I was looking at was the .Sort Does that even work with builtin array lists? Figured that would be easy because then I could just pick the (0)element and it would give me back a different one each time…

I’m new to scripting…Obvious? :slight_smile:

Thanks

1 Like

Easy! :slight_smile:

var MyArray = new Array("HiggyB", "bedalowe", "unknown");
var MyIndex = Random.Range(0,(MyArray.length - 1));
Debug.Log(MyArray[MyIndex]);

You’ll use Random.Range to get an index that’s within the length of the array than use that as a lookup value to pull the random piece of information.

No, it wouldn’t give you something different every time nor would it be the least bit random. Sort the alphabet (ascending or descending sort), now always pull the first item and you will get a very predictable and very un-random set of results. Sorting has nothing to do with what you’re after so don’t muddy your thoughts with this just yet. :slight_smile:

Just to note, that should be

var MyIndex = Random.Range(0, MyArray.length);

The upper range when using integer values is non-inclusive. (For precisely this reason–using ranges this way is common, so you get easier to read code.)

–Eric

Wow, this forum is great! Instant responses!

Thanks all for your help, guys. I’ll try these out!

Jason

Good catch Eric, thanks for covering me on that!

One last question before I dive in. I read that
the built in arrays are much faster. Currently that’s what I’m using
ie. var values : float[ ];

In your example you are using Normal Javascript Array, correct. More expensive yeah? I’m looking to go to Iphone…

The technique above works for builtin arrays just fine, and yes they are faster if you can live with them having a fixed size/length and having all one data type within them.

Ok. Thanks again. I’ll give it a try.

var MyArray = new Array(“HiggyB”, “bedalowe”, “unknown”);
var MyIndex = Random.Range(0,(MyArray.length));
Debug.Log(MyArray[MyIndex]);

var myArray : GameObject[ ];
var MyIndex = Random.Range(0,(MyArray.length));
Debug.Log(MyArray[MyIndex]);

  1. var myArray : GameObject[ ];
  2. var myIndex = Random.Range(0, myArray.length);

stripped out all other code to check just these two lines. Still getting this error

“Object reference not set to an instance of an object”
referring to the 2nd line…

I have my Array filled with 3 GameObject in the inspector.

What would this error be coming from?

Thanks

That will work…are you sure there are no other errors in the console?

–Eric

…that was probalby confusing. didn’t mean the top part. just this…

  1. var myArray : GameObject[ ];
  2. var myIndex = Random.Range(0, myArray.length);

stripped out all other code to check just these two lines. Still getting this error

“Object reference not set to an instance of an object”
referring to the 2nd line…

I have my Array filled with 3 GameObject in the inspector.

What would this error be coming from?

Thanks


JRob

Here’s the whole error…

NullReferenceException:Object reference not set to an instance of an object
UnityScript.Lang.Extensions.get_length (System.Array a)

And it repeats it 3 times…

Actually I did figure that out. :slight_smile: Sounds like you might have the code outside a function…declaring variables outside functions is fine, but code that “does stuff” should be inside.

–Eric

+1 This is an example of how to fix that:

var myArray : GameObject[];

function Start () {
  var myIndex = Random.Range(0, myArray.length); 
  Debug.Log(myArray[myIndex]);
}

aha! I’ll try that out. Thanks.

The random is now working…but :slight_smile:

I created two variables that I am using to randomly pull gameobjects (4 objects are in my Index) from an array and move to a specified location

Var myIndex1…
Var myIndex2…

It breaks when you the variable tries to get the same object so I tried the following “if” statements…

If (Index2 == Index1) {
	Index2 += 1;
}

This helps unless it goes out of range so I did this…

If (Index2 == 3) {
Index2 == 1;
}

That way I thought if it goes out of range it can just set it to one.

Doesn’t work…Seems like an easy way to do it. What is wrong here? Or is there an easier, more effieciant way?

Thanks

Jason

I think a whle statement might make more sense here???

while (myIndex1 == myIndex2) {
  myIndex2 = Random.Range(0, myArray.length);
}

No errors, but not working still…

Tip: please start using the Code button, or manually wrap code in a code block ([ code ]…[ /code ], without the spaces) when you post code here on the forums. It helps with formatting, I’m going to edit your posts so you can see for yourself.

So, you want to pull two random items from an array now, and ensure that those two items are not the same? Sure, you can use a while loop as a relatively inelegant solution:

var myIndex1 = Random.Range(0, myArray.length);
var myIndex 2 = Random.Range(0, myArray.length);
while (myIndex2 == myIndex1) { 
  myIndex 2 = Random.Range(0, myArray.length);
}

That while loop should run until something other than the first index value is pulled. If you say “but not working still” then please be specific, what about it is not working? Script error? Pulling duplicate items? Never exits the while? Please note that you might sit in that while loop for quite some time before it randomly pulls some other value, which is why that’s not such an elegant solution.

Another would be to, on the fly, create a temporary array that is nothing but indices, then grab and remove from that array. Example:

myArray = new Array("Tom", "Joe", "Amir", "Jeff");
	
// Populate the array of indices
myIndices = new Array();
for (var i = 0; i < myArray.length; i++) {
  myIndices.Push(i);
}

// Pull one index from the array and remove it
var myIndexPull = Random.Range(0, myIndices.length);
myIndex1 = myIndices[myIndexPull];
myIndices.RemoveAt(myIndexPull);
	
// Pull another index from the array and remove it as well
myIndexPull = Random.Range(0, myIndices.length);	
myIndex2 = myIndices[myIndexPull];
myIndices.RemoveAt(myIndexPull);
	
Debug.Log(myIndex1 + " and " + myIndex2);

Everytime you’re guaranteed to get two different values as you’re pulling from a list of “available” indices.