- Home /
The question is answered, right answer was accepted
Choosing a random GameObject out of an array?
I am making a script that lets an airplane choose the city it will land in, using an array. This is what I have-
#pragma strict
var allcities : Array; //an array of all the cities on the map
var takeoff : String; //where the plane has taken off from
var landing : GameObject; //where the plane will land
function Start () {
allcities = GameObject.FindGameObjectsWithTag("City"); //putting all the cities on the map into an array
var i = Random.Range(0, allcities.Length);
landing = allcities[i];
}
However, when I run the script, the landing var in the inspector remains the same. No errors or warnings occur, just the script does not seem to function. I threw in some Debug.Log's, but I cannot seem to find the problem.
Before that, I had condensed the script to this-
#pragma strict
var allcities : Array; //an array of all the cities on the map
var takeoff : String; //where the plane has taken off from
var landing : GameObject; //where the plane will land
function Start () {
allcities = GameObject.FindGameObjectsWithTag("City"); //putting all the cities on the map into an array
landing = allcities[Random.Range(0, allcities.Length)];
}
The only reason I broke it up was so that I could find the problem easier.
Any ideas?
Only Javascript please
Fairly Urgent
Do you have several game objects tagged "City" in your scene ? Can you tell us what is the value of allcities.Length and what is the value of the var i ?
Just like what $$anonymous$$iraSensei was hinting at. It might just be that only one object is tagged with "City", lol.
Also, take note that the inspector doesn't immediately update unless it has input that causes it to refresh/redraw
You should declare allcities as GameObject[] ins$$anonymous$$d of Array:
var allcities: GameObject[];
Array refers to the JS Array class, which's very slow and problematic.
Answer by sandhillceltic · Nov 16, 2013 at 02:23 AM
Ahh, found the problem. Its wasn't that there's only one object tagged city (lol, there are 12), it was that allcities.Length should have been allcities.length...calling an action not a var.
Thanks guys!!