the eroor is : array index is out of range

using UnityEngine;

using System.Collections;

public class Spawner : MonoBehaviour {

public Shape[] m_allShapes;



Shape GetRandomShape()
{

	int i = Random.Range(0,m_allShapes.Length);

	if (m_allShapes*)*
  •   {*
    

return m_allShapes*;
_
}_
_
else*_
* {*
* Debug.LogWarning(“WARNING! Invalid shape in spawner!”);*
* return null;*
* }*
* }*
* public Shape SpawnShape()*
* {*
* Shape shape = null;*
* shape = Instantiate(GetRandomShape(), transform.position, Quaternion.identity) as Shape;*
* if (shape)*
* {*
* return shape;*
* }*
* else*
* {*
* Debug.LogWarning(“WARNING! Invalid shape in spawner!”);*
* return null;*
* }*
* }*
}

lets say you have an array of length 5. You random a number between 0 and 5 and ends up being 5. Now when you go reference the object you will get the error:

m_allShapes[5] ---> Error Index out of range

Why?

its because the first object in an array is at position 0 not position 1. Meaning the rest of the objects will be in the following position:

Object 1 = m_allShapes[0]
Object 2 = m_allShapes[1]
Object 3 = m_allShapes[2]
Object 4 = m_allShapes[3]
Object 5 = m_allShapes[4]

To fix this use the code:

int i = Random.Range (0,m_allShapes.Length -1);