Peter Willemsen
Peter Willemsen

Reputation: 735

Unity3D debug magically removes NullReferenceException?

A friend of mine, which in a programmer too, has got stuck in some really weird stuff... I can't really explain it, because this code:

try {
   result = chunks.Find (delegate(float[] fa2) {
//                                            Debug.Log("fa2: " + fa2);
//                                            Debug.Log("fa: " + fa);
       return fa2[0] == fa[0] && fa2[1] == fa[1] && fa2[2] == fa[2];
   });
}
catch (Exception e) {
   Debug.LogError("result1: " + e);
}

Returns

result1: System.NullReferenceException: Object reference not set to an instance of an object
 at March+<BuildLand>c__AnonStorey0.<>m__3 (System.Single[] fa2) [0x00009] in C:\Users\Roy\Documents\March\Assets\Scripts\March.cs:262
 at System.Collections.Generic.List`1[System.Single[]].GetIndex (Int32 startIndex, Int32 count, System.Predicate`1 match) [0x00000] in <filename unknown>:0
 at System.Collections.Generic.List`1[System.Single[]].Find (System.Predicate`1 match) [0x00000] in <filename unknown>:0
 at March.BuildLand () [0x0012c] in C:\Users\Roy\Documents\March\Assets\Scripts\March.cs:257

But if you uncomment the debug lines, it works. Can anyone clarify this, please? Thanks for your help!

Upvotes: 1

Views: 1017

Answers (1)

MichaelTaylor3D
MichaelTaylor3D

Reputation: 1665

It looks like your code is getting a null reference exception, by using the try-catch statement your telling your program to ignore the error and continue running.

The catch statement catches the error and allows you to handle the error however you see fit. In your case, your error handling is just writing the error to the log.

By commenting out the Debug statement your not handling your error at all. Your essentially completely ignoring that block of code if and when an error occurs. Sometimes the program can "appear" to still run properly if that block of code doesn't have any dependencies.

However you should track down your null reference exception and resolve it or face the wrath of unintended consequences.

Upvotes: 3

Related Questions