嗚嗚喔學習筆記: 九月 2019

搜尋此網誌

2019年9月23日 星期一

Unity 2018 Detect Missing or none (偵測Mssing reference 或 None)

https://stackoverflow.com/questions/58055025/unity-how-to-detect-sprite-mssing-or-null/58056372#58056372
問題我直接發在Stackoverflow 有人解答了

如何判斷是 Missing 還是 None
主要是None可能沒問題 因為可能是Runtime再設定Sprite, 如果是Missing 一定有漏了什麼了0.0

enter image description hereenter image description here

不過有個坑點在於
本來可以這樣 :

   
        var spSprite = new SerializedObject(Img).FindProperty("m_Sprite");
        //Missing or none
        if (spSprite.objectReferenceValue == null)
        {
            if (spSprite.objectReferenceInstanceIDValue == 0)
            {
                Debug.LogFormat("Sprite == none");
                //The sprite is none
            }
            else
            {
                Debug.LogFormat("Sprite == missing");
                //The sprite is missing
            }
        }

不過可能新版Unity 改了... (unity2018 以後??)參考這篇
https://forum.unity.com/threads/there-is-no-way-to-detect-whether-a-field-is-missing-or-none.583795/
所以只能用Catch Exception 方式做了
   
public void CheckReference(Object reference)
{
    try
    {
        var blarf = reference.name;
    }
    catch (MissingReferenceException) // General Object like GameObject/Sprite etc
    {
        Debug.LogError("The provided reference is missing!");
    }
    catch (MissingComponentException) // Specific for objects of type Component
    {
        Debug.LogError("The provided reference is missing!");
    }
    catch (UnassignedReferenceException) // Specific for unassigned fields
    {
        Debug.LogWarning("The provided reference is null!");
    }
    catch (NullReferenceException) // Any other null reference like for local variables
    {
        Debug.LogWarning("The provided reference is null!");
    }
}