본문 바로가기
개발/UNITY

[UNITY]Null Reference Exception이란 무엇입니까?

by MNMNMNMN 2020. 7. 24.
728x90

Null Reference Exception이란?


어떤 오브젝트에도 참조하고 있지 않는 참조 변수에 액세스하려고 하면 NullReferenceException이 발생합니다.

참조 변수가 오브젝트를 참조하지 않으면 그것은 null로 취급될 것입니다.

변수가 “NullReferenceException”을 실행함에 따라 null일 때 실행시 오브젝트에 액세스하려고 하는 것을 알려줍니다.

C# 및 JavaScript의 참조 변수는 C 및 C++ 포인터의 개념과 비슷합니다. 어떤 오브젝트도 참조하고 있지 않은 것을 나타 내기 위해 참조 형식은 null이 기본입니다.

그러므로, 참조 되고 있는 오브젝트에 액세스하고, 없으면NullReferenceException을 얻습니다.

 

코드에서 NullReferenceException을 얻는 것은, 사용하기 전에 변수의 설정을 하지 않은 것을 의미합니다.

 

오류 메시지는 다음과 같습니다:

NullReferenceException: Object reference not set to an instance of an object
  at Example.Start () [0x0000b] in /Unity/projects/nre/Assets/Example.cs:10 
//c# example
using UnityEngine;
using System.Collections;

public class Example : MonoBehaviour {

    // Use this for initialization
    void Start () {
        GameObject go = GameObject.Find("wibble");
        Debug.Log(go.name);
    }

}
반응형

Null 체크

이것이 일어나면 당황스러울 수 있지만, 그것은 스크립트를 더 신중히 해야 한다는 것을 의미합니다.

이 간단한 예제의 해결책은 다음과 같이 코드를 변경하는 것입니다:

using UnityEngine;
using System.Collections;

public class Example : MonoBehaviour {

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

}
728x90

Try/Catch 블록

NullReferenceException의 또 다른 이유는 인스펙터에서 초기화해야 하는 변수를 사용하는 것입니다.

이것을 잊으면 해당 변수는 null이 됩니다. NullReferenceException에 대처하기 위한 다른 방법은 try/catch 블록을 사용하는 것입니다.

예를 들면, 다음의 코드:

using UnityEngine;
using System;
using System.Collections;

public class Example2 : MonoBehaviour {

    public Light myLight; // set in the inspector

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

}

 

[출처]https://docs.unity3d.com/kr/530/Manual/NullReferenceException.html

728x90
반응형

댓글