facebook twitter hatena line email

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

提供: 初心者エンジニアの簡易メモ
移動: 案内検索
(GameObject.Findで、NullReferenceException発生)
(対策方法4)
行69: 行69:
  
 
===対策方法4===
 
===対策方法4===
上の対策方法でも良いが、go?とnull判定してもよい。
+
上の対策方法でも良いが、go?とnull判定できるが、挙動がおかしいらしい。
 
<pre>
 
<pre>
 
Debug.Log(go?.name);
 
Debug.Log(go?.name);
 
</pre>
 
</pre>
 +
参考:https://light11.hatenadiary.com/entry/2019/09/01/223507

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

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);

参考:https://light11.hatenadiary.com/entry/2019/09/01/223507