개발툴/Unity

Null 레퍼런스 예외 해결방법

가든_ 2023. 7. 28. 14:51
  • 오브젝트를 레퍼런스하지 않는 레퍼런스 변수에 엑세스하려고하면 발생한다.
  • 레퍼런스 변수가 오브젝트를 참조하지 않는 경우 null로 처리되고, NullReferenceException을 표시한다.

해결방법

  1. Null 체크
    • 변수를 사용하기 전에 변수가 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");
        }
    }
}
  1. Try/Catch 블럭
    • 사용하려는 변수를 설정하지 않으면 try 블럭에서 NullReferenceException이 발생하고, catch 블럭에서 픽업한다.
    • 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");
        }
    }