Quantcast
Channel: Answers for "Missing GameObject and Null do not test the same, but how do I test for missing?"
Viewing all articles
Browse latest Browse all 12

Answer by huulong

$
0
0
As DriesVienne wrote, using an Observer pattern, messaging system or the like if probably your best bet to cleanly set your references to null before objects are actually destroyed. Unity is using a trick to distinguish null and missing values, and on top of that you cannot call a method on a null/missing object, so I had to find foolish to weird workarounds. In any case you should use them for debugging purposes only: - `Debug.Log(obj)` null -> outputs `Null` (but an empty string if concatenated) missing -> outputs `null` - string.Format("{0}", obj) null -> `""` missing -> `"null"` - bool isMissing = (obj ?? (object) "missing").ToString() == "missing"; null -> `false` missing -> `true` I borrowed the last one from an answer to [How to do ToString for a possibly null object?][1] but you need to create a small string, or anything you can cast to an object and then compare to distinguish from null. An alternative expression that does use strings is `(obj ?? (MyClass) new MyClass()) != null` but it requires creating a temporary object of your type... Tested on: a sub-class of `EditorWindow`, to check whether my window reference was missing after I closed it. [1]: http://stackoverflow.com/questions/3987618/how-to-do-tostring-for-a-possibly-null-object

Viewing all articles
Browse latest Browse all 12

Latest Images

Trending Articles





Latest Images