Search Unity

GameObject Array index out of bound

Discussion in 'Scripting' started by mealphamale, Feb 15, 2014.

  1. mealphamale

    mealphamale

    Joined:
    Feb 10, 2014
    Posts:
    7
    It sounds silly but I'm stuck here with this error.

    I've declared an array like this:
    Code (csharp):
    1.  
    2. int x = 0;
    3. public GameObject[] emptyArr = new GameObject[5];
    And I was trying to assign it a game object like this:

    Code (csharp):
    1.  
    2. print("x" + x);
    3. // print("x" + emptyArr[x]);
    4. emptyArr[x] = (GameObject)Instantiate(obstacle, new Vector3(transform.localPosition.x + 5.0f, y, 0),Quaternion.identity) as GameObject;
    5. x++;
    6.  
    And it throws:

    Code (csharp):
    1. IndexOutOfRangeException: Array index is out of range.
    2. (wrapper stelemref) object:stelemref (object,intptr,object)
    3. SpawnObstacle.Spawn () (at Assets/SpawnObstacle.cs:81)
    I'm not trying to "access" the game object array, but I was trying to assign something to it, then why throw this error in the first place?
     
    Last edited: Feb 15, 2014
  2. mealphamale

    mealphamale

    Joined:
    Feb 10, 2014
    Posts:
    7
    It's ok, I've solved it.... the problem was I declared GameObject as Public..
     
  3. starkister

    starkister

    Joined:
    Aug 30, 2014
    Posts:
    1
    Oh,I got same problem, thank you!