facebook twitter hatena line email

「Unity/Csharp/Exception/NullReferenceException」の版間の差分

提供: 初心者エンジニアの簡易メモ
移動: 案内検索
(SerializeFieldで、NullReferenceException発生)
(GameObject.Findで、NullReferenceException発生)
行66: 行66:
 
     }
 
     }
 
}
 
}
 +
</pre>
 +
 +
===対策方法4===
 +
上の対策方法でも良いが、go?とnull判定してもよい。
 +
<pre>
 +
Debug.Log(go?.name);
 
</pre>
 
</pre>

2023年10月17日 (火) 18:21時点における版

SerializeFieldで、NullReferenceException発生

以下SerializeFieldのtextに、オブジェクトを入れなかった場合、NullReferenceExceptionが発生する。

詳細エラー

NullReferenceException: Object reference not set to an instance of an object

サンプル

using UnityEngine;
using UnityEngine.UI;

public class NullReferenceExceptionScene : MonoBehaviour
{
    [SerializeField] Text text;
    void Start()
    {
        text.text = "hoge";
    }
}

対応方法1

is not nullを使う(これが一番良いかも)

if (text is not null)
{
    text.text = "hoge";
}

対応方法2

null判定する

if (text != null)
{
    text.text = "hoge";
}

対応方法3

ReferenceEqualsを使う

if (!ReferenceEquals(text, null))
{
    text.text = "hoge";
}

参考:https://bluebirdofoz.hatenablog.com/entry/2022/09/18/234745

GameObject.Findで、NullReferenceException発生

GameObject.Findで存在しない、オブジェクト名を入れると、NullReferenceExceptionが発生する。

詳細エラー

NullReferenceException: Object reference not set to an instance of an object

サンプル

public class NullReferenceExceptionScene : MonoBehaviour
{
    void Start()
    {
        GameObject go = GameObject.Find("test");
        Debug.Log(go.name);
    }
}

対策方法4

上の対策方法でも良いが、go?とnull判定してもよい。

Debug.Log(go?.name);