Search Unity

  1. We are migrating the Unity Forums to Unity Discussions by the end of July. Read our announcement for more information and let us know if you have any questions.
    Dismiss Notice
  2. Dismiss Notice

Unity5 - Instantiate bug?

Discussion in 'Getting Started' started by Ridd, Mar 28, 2015.

  1. Ridd

    Ridd

    Joined:
    Mar 28, 2015
    Posts:
    4
    Hello !
    Firstly, I would like to say that my english is not pretty good so sorry for that ;)
    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.

    Code (CSharp):
    1. public class pipes : MonoBehaviour {
    2.    
    3.     public GameObject[] obj;
    4.     public float spawnMin = 1f;
    5.     public float spawnMax = 2f;
    6.    
    7.     void Start () {
    8.         Spawn ();
    9.     }
    10.    
    11.     void Spawn() {
    12.         Instantiate(obj[Random.Range(0, obj.Length)], transform.position, Quaternion.identity); //here
    13.         Invoke("Spawn", Random.Range(spawnMin, spawnMax));
    14.     }
    15. }
    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!
     
  2. JasonBricco

    JasonBricco

    Joined:
    Jul 15, 2013
    Posts:
    956
    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.
     
    Last edited: Mar 28, 2015
    Kiwasi likes this.
  3. Ridd

    Ridd

    Joined:
    Mar 28, 2015
    Posts:
    4
    Code (CSharp):
    1. public GameObject[] obj;
    forum.jpg
     
  4. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    21,769
    Code (CSharp):
    1. void Spawn() {
    2.     Instantiate(obj[Random.Range(0, obj.Length)], transform.position, Quaternion.identity); //here
    3.     Invoke("Spawn", Random.Range(spawnMin, spawnMax));
    4. }
    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.
     
    Ridd likes this.