[TIL] Unity Null Check
Background
In Unity, dealing with null checks for objects is a common task. However, there are some misconceptions regarding how to handle null checks. This article explores these misconceptions and the correct practices to avoid unexpected results. The test code for this article can be referenced here.
Fake Null
When we declare a serialized Unity object as null, for example public Object obj = null , it’s not actually a true null. This is because Unity needs to display this field in the editor and provide additional error messages. Therefore, these fields are set as a ‘fake null’ object rather than a true null.
Destroy() and DestroyImmediate()
In Unity, we can use Destroy()or DestroyImmediate() to destroy objects in the game. However, it’s important to note that while the object on the C++ side has been destroyed, the C# side’s ‘wrapper object’ will only be collected by the garbage collector (GC). To prevent developers from invoking functions on the object after it’s been deleted, Unity has overridden the == operator to return null.
Correct Practice
Based on the above research, we should only use == to check if a Unity object is null. Syntax sugars like is null , ?. , ?? should not be used, as these constructs are not overridden by Unity and might result in unexpected outcomes in the game.
Conclusion
In Unity, null checks are a common issue that we frequently encounter. We must be aware of the peculiarities of Unity objects and the correct practices for null checks. This way, we can avoid errors caused by misuse of null checks and ensure the normal operation of the game.
背景
在 Unity 中,我們經常需要處理物件的 null 檢查。然而,對於檢查 null 的處理方式有一些誤區。本文將探討這些誤區以及正確的做法,以避免產生預期外的結果。本文的測試程式碼可以參考這裡。
假的 null
當我們將一個序列化的 Unity 物件「宣告」為 null 時,例如 public Object obj = null,實際上它並不是真正的 null。這是因為 Unity 需要在編輯器中顯示這個欄位以及提供更多的錯誤訊息。因此,這些欄位被設置為一個「假的 null」物件,而非真正的 null。
Destroy() 和 DestroyImmediate()
遊戲中,我們可以使用 Destroy()或 DestroyImmediate() 來銷毀物件。然而,需要注意的是,雖然 C++ 端的物件已經被銷毀,但是在 C# 端的「包裝物件」要等到垃圾回收(GC)才會被回收。為了避免開發者在刪除物件後繼續調用該物件的功能,Unity 改寫了 == 運算子,使其回傳 null。
正確的做法
根據上述研究我們可以得知,我們應該只使用 ==來判斷 Unity 物件是否為 null。不能使用像 is null 、?. 、?? 這樣的語法糖,因為這些寫法都未被 Unity 覆寫,可能會導致遊戲產生預期外的結果。
總結
在 Unity 中,null 檢查是我們經常需要處理的一個問題。我們必須意識到 Unity 物件的特殊性以及對於 null 檢查的正確做法。如此,我們才能避免由於誤用 null 檢查而產生的錯誤,並確保遊戲的正常運行。
Get bwaynesu’s stories in your inbox
Join Medium for free to get updates from this writer.
參考資料:

![[TIL] Unity UniTask — Zero GC Async/Await to Replace Coroutines](https://miro.medium.com/v2/resize:fit:1358/format:webp/1*TTjVLV8OO6y7ryuOWVa3tg.png)
![[TIL] Unity — Assembly Definitions](https://miro.medium.com/v2/resize:fit:1358/format:webp/1*FIG-tr31Vjdy_XvDRLb7sQ.png)




