foreach iteration variable.. null?

i hope i’m not missing something obvious here, but this is the first time i’ve truly been stumped with unity and actually had to come make my own post

there’s nothing that crazy about this loop, but it didn’t work as expected, and upon stepping through it, well… how can h be null?

alt text

it also seems to completely step over certain lines within for no reason, i’ve no clue what’s going on here. i’ve had bugs before with unity where it sort of loses its place among the lines of code, but restarting it/visual studio usually fixes things. this time, no dice

Well, there could be several reasons why the debugger behaves strange “visually”. First of all keep in mind that there is no “for” or “foreach” thing in the common intermediate language. Therefore what code results from a given for / foreach loop depends on the used compiler. Unity uses the Mono C# compiler while visual studio works on the basis of the .NET C# compiler. So those slight differences might result in this weird visual behaviour. Keep in mind that one line of highlevel code often belongs to several lines of IL code. So for a debugger to “step” through the highlevel code it has to know what statements / opcodes belong to the actual source code line.

One reason could be your goto statement. It breaks the usual construct of a foreach loop so VS might not even recognise the foreach properly. I suggest you have a look at the IL code that was generated by using ILSpy on your compiled assembly and switch the language to “IL” to see the “actual” code. The decompilation from IL to C# is usually quite good, however as i said a decompiler can only “assume” based on some opcode patterns what high level code has generated the given IL code.

While it’s possible to omit the body brackets of loops and if statements if it only contains a single statement i strongly would recommend to only use this when the statement really is just a single line. Such a complex nested loop–>if–>loop is just confusing and it’s easy to miss the exact flow. Code is mainly meant to be easy to write, read and understand by humans. Do not use certain techniques because it’s shorter or quicker to write but because it actually improves readability.