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:
I believe I have set up the public Material correctly. The array has two materials assigned to elements 0 and 1
The code actually works ie. the button changes colour correctly, but I still get the error message
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.
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.
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
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