Getting "IndexOutOfRangeException: Index was outside the bounds of the array."

Hi Everyone

I get the following error when running a unity simulation I am developing:
“IndexOutOfRangeException: Index was outside the bounds of the array.”

I have some code that changes the colour of a button depending on whether or not the simulation is running; red for not running and green for is running. This is the code that causes the problem:

public Material[ ] button_material;
Renderer rend;

private void Update()
{
//Change the button colour
rend = GetComponent();
rend.enabled = true;
if (Global_Variables_Manager.instance.Run_Sim)
{
rend.material = button_material[0]; //Green
}
else
{
rend.material = button_material[1]; //Red
}
}

The keys points are:

  1. I believe I have set up the public Material correctly. The array has two materials assigned to elements 0 and 1
    5310903--533847--upload_2019-12-24_11-43-5.png
  2. The code actually works ie. the button changes colour correctly, but I still get the error message
  3. When, clicking on the error messages , it takes me to the rend.material = button_material[0] line in the script or rend.material = button_material[1] in the code above.

Any suggestions?
Thanks
Rob

1 Like

Looks like it is set up correctly. Look around your scene for another instance of this script, one where you did not fill in those materials, but perhaps mis-dragged.

To find this easily, either use “t:MyScriptName” in the search field of the scene, or make a Start() function and do Debug.Log(name); and it will tell you which GameObject this script is on.

3 Likes

Well, Im coming back to this after quite a while. However, I have added Debug.Log(name); and confirmed that the script is running precisely where I expect it to run and the material array for that gameobject is as listed above. As before, everything still runs, the material changes colour as expected, I just get this error message. Quite annoying really

WHOA! Two years… and what a two years it was! Welcome back!!

Try these steps:

  1. print out the size of the array before accessing it.

  2. comment out the array index lines of code above - does the error still happen? then the bug is elsewhere

Here’s my standard blurb:

Here are some notes on IndexOutOfRangeException and ArgumentOutOfRangeException:

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

Steps:

  • find which collection it is (critical first step!)
  • find out why it has fewer items than you expect
  • remember you might have more than one instance of this script in your scene/prefab
1 Like

Yeah nothing like a Covid lockdown to provide time to think about old projects. Anyway, you were pretty much spot on. It looks like I accidentally attached that script to a place it was never meant to go. Thanks very much for your help

1 Like