IndexOutOfRangeException: Array index is out of range when using an Array and instantiating

Within my level i’m wanting to spawn some collectible coins throughout the level at certain points. This is my code i currently have for instantiating a coin prefab at desired spawn points:

var coin : GameObject;
var coinspawn: Transform[];

function OnTriggerEnter(other : Collider){
        if (other.tag == "Player"){
	    for (var i = 0; i < coinspawn.length; i++);
        var coinClone : GameObject = Instantiate (coin, transform.position, transform.rotation);
     	coinClone.transform.position = coinspawn*.position;	*
  • }*
    }
    The problem i’m having is that Unity says IndexOutOfRangeException: Array index is out of range. and points to my coinClone.transform.position = coinspawn_.position; line as the problem but i’m none the wiser as to what exactly it means in my situation._
    As it stands Unity flags the error and when i continue all the clones have been instantiated but just not at the spawn points. What am i doing wrong?

The error means that the value of i is too large in this case. i is always coinspawn.length in your script because your for-loop-body is empty! The loop will run through all iterations and after it is finished only one coin is created. I guess you want the prefab instantiation to be inside the loop body:

var coin : GameObject;
var coinspawn: Transform[];

function OnTriggerEnter(other : Collider)
{
    if (other.tag == "Player")
    {
        for (var i = 0; i < coinspawn.length; i++)
        {
            var coinClone : GameObject = Instantiate (coin, transform.position, transform.rotation);
            coinClone.transform.position = coinspawn*.position;* 
 *}*
 *}*
*}*
*```*

Thanks Bunny 83, this now works as intended! :slight_smile: