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*.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
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*.sprite == null)*
{
nullFound = true;
break;
}
}