# Can someone explain this to me?

Discussion in 'Scripting' started by PenguinLord, Jan 11, 2017.

1. ### PenguinLord

Joined:
Sep 27, 2013
Posts:
9
I'm no good with for loops.

My friend wrote this and i didn't fully understand it when he explained, so if anyone can explain simply how it works, i know what it is supposed to do but does not work, so i want to understand it before i fix it.

Code (CSharp):
1. public bool CheckifDone()
2.     {
3.
4.         bool done = true;
5.         for (int i = 0; i < Alive.Count; i++)
6.         {
8.             for (int x = 0; x < Dead.Count; x ++)
9.             {
11.                 {
13.                 }
14.             }
16.             {
17.                 done = false;
19.             }
20.
21.         }
22.         for (int y = 0; y < toKill.Count; y++)
23.         {
24.             Alive.Remove(toKill[y]);
25.         }
26.
27.         return done;
28.
29.     }

2. ### LeftyRighty

Joined:
Nov 2, 2012
Posts:
5,148
Ok, so what is it supposed to do?

3. ### ericbegue

Joined:
May 31, 2013
Posts:
1,294
That.

Code (CSharp):
1.             for (int x = 0; x < Dead.Count; x ++)
2.             {
4.                 {
6.                 }
7.             }
And, the array is modified while you iterate over it... wait. If you enter that if-block, you'll be stuck in an infinite loop, because the last element added to the Dead will be always Alive\[i\] .

4. ### LiterallyJeff

Joined:
Jan 21, 2015
Posts:
2,767
Without knowing anything about the purpose of this code, and without knowing what these array types are, here are my comments as I read through it:

Code (CSharp):
1. public bool CheckifDone() {                   // we're checking if something is done
2.
3.     bool done = true;                         // initialize done to true
4.     for(int i = 0; i < Alive.Count; i++) {    // for each alive thing
6.         for(int x = 0; x < Dead.Count; x++) { // for each dead thing
7.             if(Alive[i] == Dead[x]) {         // if the dead thing is the same object as the alive thing
9.             }
10.         }
11.         if(inDead == false) {                 // this is guaranteed false, because nothing changed it from earlier
12.             done = false;                     // guaranteed to be set, due to above
13.             toKill.Add(Alive[i]);             // kill the alive thing (this will be done for all alive things, due to above)
14.         }
15.
16.     }
17.     for(int y = 0; y < toKill.Count; y++) {   // loop through all things to kill (all alive things, due to above)
18.         Alive.Remove(toKill[y]);              // remove them from the alive list (Alive list now empty)
19.     }
20.
21.     return done;                              // this will always return false, due to above
22.
23. }

johne5 likes this.
unityunity