IndexOutOfRangeException: Index was outside the bounds of the array (859106)

I am using this code to change between displays.

but I get this error
IndexOutOfRangeException: Index was outside the bounds of the array.
Cycle.Update () (at Assets/Cycle.cs:12)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Cycle : MonoBehaviour
{

    void Update ()
    {
        if (Input.GetKeyDown("space"))
        {
            Display.displays[2].Activate();
        }
      
    }
       
}

Index out of bounds means just what it says. The index you use to access an array is outside the bounds of the array, ie you are trying to access an element that does not exist index-wise.
You only have one array in your code and only access it at one location. Soo… :slight_smile:

Then it’s outside the bounds of your array.

Remember collections are 0 based, so if you have 2 displays, it’s 0 and 1, not 1 and 2.

Everything Yoreki and Brath says above, plus my $0.02 catch-all:

Here are some notes on IndexOutOfRangeException and ArgumentOutOfRangeException:

http://plbm.com/?p=236

Steps to success:

  • find which collection it is (critical first step!) (in this case it’s pretty obvious)
  • find out why it has fewer items than you expect
  • fix whatever logic is making the indexing value exceed the collection
  • remember you might have more than one instance of this script in your scene/prefab