if ALL items in array are something
Hi, I having some trouble finding out how to do a check to see if all instances in an array are equal to something not just the first one. I am having trouble finding the right question around the forums too. Everything that I try has the same outcome, just testing the first array item.
This is what I have
for(int i=0; i < slots.Length; i++)
{
if (slots[i].sprite != null)
{
nIndex = i;
}
}
So this I thought would check each item in the array to see when none of the items are null, so when all the items are set to a sprite. But it only checks the first item. That would be great if the inventory was only set to one carrying weight!
Thanks guys
Your loop looks fine. If your loop is only checking the first position, then there must be a problem with the way that you are creating the "slots" array. Try
Debug.Log("Length of slots array: " + slots.Length);
for(int i=0; i < slots.Length; i++)
{
if (slots[i].sprite != null)
{
nIndex = i;
}
}
And see what it prints out.
Answer by NoseKills · Dec 11, 2015 at 11:58 PM
But it only checks the first item.
Why do you think so? The only exit condition for your loop is i < slots.Length
so you do check every item and set nIndex
to be 'i' every time the sprite is not null. So after the looping, nIndex has the value of the last non-null item index in the array.
To answer your question, you have basically 2 options. Either check that all items fulfill your condition or check if even one item doesn't fulfill it. The latter way makes more sense because if you find even one item that fails the check, you don't even need to check the rest and you can break out of the loop.
bool nullFound = false;
for(int i=0; i < slots.Length; i++)
{
if (slots[i].sprite == null)
{
nullFound = true;
break;
}
}