I'm trying to figure out how to get rid of my IndexOutOfRange error in Unity. I've tried a couple of different things, but I'm at a loss.
Its just that when I press tab, I cycle through my Game Objects array as planned, but then when you get to the last one, it throws that. I'd like for it to cycle back to the beginning, if possible. I've been plugging at this for probably 2 days now.
This is what I have so far (I only included the important variables, cause this script is huge)
int currentWindow = 0;
public GameObject theUI;
public GameObject[] windows;
void Update()
{
//Toggle Menu
if (Input.GetKeyDown(KeyCode.Escape))
{
if (theUI.activeInHierarchy)
{
theUI.SetActive(false);
}
else
{
theUI.SetActive(true);
windows[0].SetActive(true);
Refresh();
}
}
//Toggle Between Windows
if (theUI.activeInHierarchy)
{
if (Input.GetKeyDown(KeyCode.Tab))
{
ToggleWindow(currentWindow);
}
}
}
public void ToggleWindow(int windowNumber)
{
if (windowNumber == currentWindow)
{
windows[windowNumber].SetActive(!windows[windowNumber].activeInHierarchy);
Refresh();
currentWindow ;
windows[currentWindow].SetActive(!windows[currentWindow].activeInHierarchy);
}
}
If anyone has any insight as to what to do, please help! I've followed a few different things, but because my windows[] array is a GameObject rather than an int or anything else, it's made it quite difficult to figure out how to fix it using other sources.
CodePudding user response:
currentWindow ;
windows[currentWindow]....
There is no check whatsoever if that index exceeds the array size.
For a simple wrap around you can use the remainder operator %
often called 'modulo' (though only same for positive values)
currentWindow = (currentWindow 1) % windows.Length;
So if the currentWindow
reaches windows.Length
it simply starts from 0
again.