If statement not working without do while loop

Updated on May 9, 2018 in [A] Unity Scripting
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
3 on May 7, 2018

Tzitle says it all.

code 1 Works

Snippet
do
            {
                for (int i = 0; i < cheatCache.Count; i++)
                {
                    cheatCache.RemoveAt(i);
                }
            } while (cheatCache.Count > 0);

Code 2 removes some but not all items

            
                for (int i = 0; i < cheatCache.Count; i++)
                {
                    cheatCache.RemoveAt(i);
                }
  • Liked by
Reply
1 on May 8, 2018

The only reason that I can see, that this code wouldn’t work:

for (int i = 0; i < cheatCache.Count; i++)
{
    cheatCache.RemoveAt(i);
}

Is if the cheatCache is null || empty; or actually equal to 0. Is the cheatCache within the scope of the function? For testing purpose you should check the value of cheatCache.Count, just before you run the for .. loop. Output it to console or something.

Lastly, since you only posted a small fraction of the code, I can assume that cheatCache is an array? In this case:

The Count() extension method is not O(n) when used on an array. All arrays implement ICollection<T> so it will end up using the ICollection<T>.Count property, it won’t enumerate all the elements in the array.From Mike Danes
Source

Try using the Length property instead of Count.

Helpful
on May 9, 2018

Made a quick video to show this. It feels like there is not enough time for the if statement to properly empty the list but the do-while loops again to make sure it happens. ther’s probably a better explanation

https://youtu.be/_jNMnS9rt5U

Show more replies
  • Liked by
Reply
Cancel
0 on May 9, 2018

Done the testing before posting. Its a list not array hence the Count property and RemoveAt function. The same fragment of code works when enclosed in the do-while loop, under same conditions.

the list is a class variable and works just fine.

  • Liked by
Reply
Cancel