- Home /
How to check an item's index in an array?
I have a script that scrolls through the numbers 1, 2 and 3. I want to make this so that when the item's index matches with the number, it gets enabled. otherwise, it is disabled.
I can enable stuff no problem, like this:
mods[currentIndex].GetComponent(script).enabled = true;
but how would I check for the index that doesn't match up with currentIndex?
if(mods[].index !== currentIndex)?
Answer by jgodfrey · Jun 15, 2016 at 10:02 PM
The easiest way might be to simply disable all items, and then enable the mods[currentIndex] item. While that's not the most efficient way, it's probably adequate unless you doing it in Update or something.
Otherwise, when you have your new "currentIndex", you could just iterate through your 3 items and enable the one matching currentIndex and disable the ones not matching currentIndex using something like:
mods[index].GetComponent(script).enabled = index == currentIndex;
Answer by Orami · Jun 15, 2016 at 11:34 PM
While jgod's answer will work for small lists you will have a lot of over head in larger lists. You will have to adapt the code a bit, but it should give you a better option I hope.
What I would suggest is using a function to change your index....
public class someClass : MonoBehaviour
{
int currentIndex = 0;
public GameObject[] mods;
void SetIndex(int newIndex)
{
mods[currentIndex].GetComponent<otherScript>().enabled = false;
mods[newIndex].GetComponent<otherScript>().enabled = true;
currentIndex = newIndex;
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612083021im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
NullReferenceException array 2 Answers
Javascript array: Negative Indexes? 2 Answers
Array Index out of range (JavaScript) 1 Answer
Array error - Index is less than 0... 3 Answers
IndexOutOfRangeExeption - Array index is out of range 2 Answers