Array index error?

I’m working towards the end of the space shooter tutorial and Unity5 is reporting this error:

IndexOutOfRangeException: Array index is out of range.
GameController+c__Iterator2.MoveNext () (at Assets/Scripts/GameController.cs:50)

This is the code I have:

            GameObject hazard = hazards [Random.Range (0, hazards.Length)];

How do I fix this?

This error means that you inserted index larger than length of the array. For example hazards[5] while your hazards array contains only 3 elements.

In your case, it may happens if hazards array is empty, in that case
Random.Range (0, hazards.Length) will be 0
but hazards[0] will be out of range

Just use Debug.Log

For example:

Debug.Log ("Length: " + hazards.Length);
int index = Random.Range (0, hazards.Length);
Debug.Log ("index: " + index);
GameObject hazard = hazards [index];

And everything will be clear