- Home /
For loop not working as intended?!? (Beginner)
So I wrote a simple for loop in the update to check if my inventory system is full but it's not working, what am I doing wrong?
for (int i = 0; i < Slots.Length; i++)
{
if(Slots[i].childCount == 1)
{
isfull = true;
}
else if(Slots[i].childCount == 0)
{
isfull = false;
}
}
isfull changes to true if all of my slots have a child as it should but if I then destroy a child, it won't make isfull false because the first if statement in this loop is somehow still changing isfull to true, even if that statement is not even applying anymore. If I just add break;
in each if statement, the isfull bool will go crazy and be true from start no matter what the condition is.
Help please :/
Answer by pankajb · May 09, 2016 at 08:20 PM
Check using something like this...
void CheckIfInventoryIsFull() {
int totalInventoryInBag=0;
for (int i = 0; i < Slots.Length; i++)
{
if(Slots[i].childCount == 1)
{
totalInventoryInBag ++;
}
}
if(totalInventoryInBag == Slots.Length)
{
isfull = true;
}
else
{
isfull = false;
}
}
Ins$$anonymous$$d of counting manually all slots that are filled and checking against the overall size, you can simply check if at least one slot is empty:
isfull = true;
for (int i = 0; i < Slots.Length; i++)
{
if(Slots[i].childCount == 0)
{
isfull = false;
break; // stop the loop since the inv can't be full if one slot is empty
}
}
I'm not entirely sure why isfull = true;
is outside of any if condition or loop but this code works perfectly fine, thank you very much!
In your code, you're setting the flag every time you go round the loop. That means that isFull ends up as whatever the last time through sets it to (regardless of whether it found an empty one earlier in the loop).
In Bunny's code it's being set to true first and then negated only if it finds one that's empty. As soon as it does find an empty one, it doesn't need to look any further so it breaks out of the loop. If it gets all the way through the loop without breaking out, then it hasn't found any empty ones and isFull is still true. That's what you're after.
There is a problem with your code, it keeps adding 100s-1000s to totalInventoryInBag with no limit. The for loop is in the update void.
void CheckIfInventoryIsFull() { } is complete method... you should only call it when you want to check isFull status. Its not a good practice to put for loop in Update method.