2018年6月12日火曜日

Unity Null Reference Exceptionとは

どのオブジェクトにも参照していない参照変数にアクセスしようとすると、NullReferenceExceptionが起こる。
NullReferenceException: Object reference not set to an instance of an object

実態がないオブジェクトにしないようにする必要があります。

(1)Nullチェックする

using UnityEngine;
using System.Collections;

public class Test: MonoBehaviour {

    void Start () {
        GameObject go = GameObject.Find("wibble");
        if (go) {
            Debug.Log(go.name);
        } else {
            Debug.Log("No game object called wibble found");
        }
    }
}


(2)Try/Catchを使う


Nullチェックか、Try/Catchをする必要があるようですね。

using UnityEngine;
using System;
using System.Collections;

public class Test2: MonoBehaviour {

    public Light myLight;

    void Start () {
        try {
            myLight.color = Color.yellow;
        }     
        catch (NullReferenceException ex) {
            Debug.Log("myLight was not set in the inspector");
        }
    }

}

0 件のコメント:

コメントを投稿