- Home /
working with array index...
I've been getting an error message telling me that:
IndexOutOfRangeException: Array index is out of range.
I tried playing with the int variable for Random.Range to get my three spawn points into "range" with nothing working.
The Code:
var spawn : Transform[];
var game_cube : Rigidbody;
var cube_count = 0;
InvokeRepeating("LaunchProjectile", 2, 3);
function Update() {
if (cube_count>= 10) {
CancelInvoke();
}
}
function LaunchProjectile () {
var randomPick : int = Random.Range(0,2);
instance = Instantiate(game_cube, spawn[randomPick].position, transform.rotation);
instance.velocity = Vector3.zero;
cube_count = cube_count +1;
}
Does it have something to do with the "Instantiate" script? Or do I have to attach this directly to the spawn points? The error is telling me there is something wrong with the "instance = Instantiate(game_cube, spawn[randomPick].position, transform.rotation);" line of code. Any ideas?
Have you attached at least 3 spawn points to your Transform[] array? What the error means is that you're asking for, say, spawn[1] but you only have one item in the array (remember that index starts at zero). Try adding a debug statement:
Debug.Log("Spawn has " + spawn.Length + " members, I'm requesting member " + (randomPick + 1));
on the line directly above your instantiate line.
Answer by aldonaletto · Oct 01, 2011 at 12:14 AM
One possible reason for these errors that seem to be cursing you maybe a second forgotten instance of this script attached to some object in your scene - you set the spawn array in one instance, but there's another one hidden somewhere complaining that its spawn array is empty.
Setting Random.Range max to spawn.length is the right thing to do: you can use how many spawn points you want, and additionally this will solve the out of range problem, no matter how many lost instances are in your scene (changes in the script instructions affect all instances automatically).
function LaunchProjectile () { var randomPick : int = Random.Range(0,spawn.length); ...Just to check the basics: remember to set the spawn size to 3 and fill the 3 elements with your spawn point objects.