[Unity] 關於判斷 Image 中參數是否為 null 的小細節 - Detecting Tricky Null Fields in Image

這是今天遇到的小問題,是關於如何判斷 Image 的 Material 為 None 的方法。

可以看到下圖中的 Image Inspector 介面有兩個欄位顯示為 None,分別對應到 Image.spriteImage.material 這兩個 API,不過這兩個 API  雖然同為 None,但在腳本中的可完全不是這回事。

1507805935946

首先,Image.sprite 顯示為 None 表示沒有 Sprite 被關聯到這個 UI 元件上,所以顯示出來是一片白,在腳本中可以跟 null 做比較,也可以設值為 null。

1
2
3
4
5
if (m_image.sprite == null) {
Debug.Log("sprite is None");
} else {
m_image.sprite = null;
}

不過,Image.material 就有點不同了,雖然 Inspector 上顯示為 None,但事實上它的值為預設的 Material,這點可以在官方文件中看到:

The default Material is used instead if one wasn’t specified. 如果沒有設值,則會用預設的 Material 代替。

所以如果要確認這個欄位是否有被設質,正確的用法應該是跟 Image.defaultMaterial 做比較,以免出現跟預期不同的邏輯結果。順帶一提,設值上還是用 null 就可以了。

1
2
3
4
5
if (m_image.material == m_image.defaultMaterial) {
Debug.Log("material is None");
} else {
m_image.material = null;
}

這個小小的細節可讓我檢查了好久阿。