Unity5 - Instantiate bug?

Hello !
Firstly, I would like to say that my english is not pretty good so sorry for that :wink:
I’m also a beginner so maybe my question is out of place.

I have been making a simple 2D game. In Unity 4 my simple sprite generator works great but in Unity 5 I have a “IndexOutOfRangeException: Array index is out of range.” on 15line in my code.

public class pipes : MonoBehaviour {
   
    public GameObject[] obj;
    public float spawnMin = 1f;
    public float spawnMax = 2f;
   
    void Start () {
        Spawn ();
    }
   
    void Spawn() {
        Instantiate(obj[Random.Range(0, obj.Length)], transform.position, Quaternion.identity); //here
        Invoke("Spawn", Random.Range(spawnMin, spawnMax));
    }
}

What is wrong with Unity5? I also made some tutorials from Live Unity and also this stuff didn’t work on version 5.

Thanks for your time!

Is that obj array initialized inside your editor? In your code you don’t initialize it, which would produce an out of range exception when trying to index into it.

1 Like
public GameObject[] obj;

2042838--132578--forum.jpg

void Spawn() {
    Instantiate(obj[Random.Range(0, obj.Length)], transform.position, Quaternion.identity); //here
    Invoke("Spawn", Random.Range(spawnMin, spawnMax));
}

My initial thought was that you appeared to be using two different minimum values for Range, but your code is working just fine for me. I created a new project, threw the script onto an object, and attached two empty objects (one named SmallPipe and one named LargePipe). Then I ran it.

I’m on Unity 5.0.0f4.

1 Like