- Home /
"For" Loop not working second time
I'm making an inventory and I'm using a "for" loop to reorganize it every time it is viewed. Basically, the reorganization just gets rid of blank slots from items that have been removed. The inventory is a string array with a max capacity of 500 items. I have a static function for reorganization:
static function reorganize () {
var tempI = new String[500];
itemsNum = 0;
var listN : int = 0;
for(var h : int = 0; h < stuff.Length; h++){
if(stuff[h] != ""){
tempI[listN] = stuff[h];
listN ++;
}
}
stuff = tempI;
itemsNum = listN;
}
"stuff" is the inventory and "itemsNum" is the number of items. I have another script that calls this function. It works perfectly the first time it's called, but the second time it doesn't detect the blank slots and says that there are 500 items. Any help would be appreciated.
Answer by Bunny83 · Mar 03, 2017 at 03:22 AM
An empty string "" is an actual string. However when you create a new string array all elements are null. So "null" is a value that is different from the empty string. That's why there's the method string.IsNullOrEmpty
which checks both if it's null or the empty string
so in your case:
if (!string.IsNullOrEmpty(stuff[h]))
Your answer
![](https://koobas.hobune.stream/wayback/20220612112332im_/https://answers.unity.com/themes/thub/images/avi.jpg)