facebook twitter hatena line email

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

提供: 初心者エンジニアの簡易メモ
移動: 案内検索
(対応方法)
(対策方法4)
行78: 行78:
 
</pre>
 
</pre>
 
参考:https://light11.hatenadiary.com/entry/2019/09/01/223507
 
参考:https://light11.hatenadiary.com/entry/2019/09/01/223507
 +
 +
==NullReferenceExceptionの出方==
 +
UnityEditorで、try-catchなし
 +
<pre>
 +
NullReferenceException: Object reference not set to an instance of an object
 +
NullCheckScene.Start () (at Assets/Scripts/Scene/NullCheckScene.cs:12)
 +
</pre>

2023年10月25日 (水) 17:26時点における版

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";
    }
}

対応方法

null判定するが、一番良いかも

参考:https://baba-s.hatenablog.com/entry/2021/11/16/090000

対応方法1

null判定する

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

対応方法2

is not nullを使う

if (text is not 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

NullReferenceExceptionの出方

UnityEditorで、try-catchなし

NullReferenceException: Object reference not set to an instance of an object
NullCheckScene.Start () (at Assets/Scripts/Scene/NullCheckScene.cs:12)