How do you resolve an object reference not set to an instance of an object in unity?

[Unity 2D]오류 해결 노트- NullReferenceException: Object reference not set to an instance of an object

Bee2021. 5. 4. 11:50

NullReferenceException: Object reference not set to an instance of an object

유니티를 배운지 얼마 되지 않았는데, 이 오류는 처음 나와서 당황했다. 눈을 부릅뜨고 스크립트를 다 외울만큼 찾아봐도 오타도 없고 잘못한 게 없는데 계속 오류가 뜨니 미칠 노릇.

거의 5시간을 이 오류 해결에 쏟아부은 것 같다.

이러다 코딩보다 먼저 구글링 달인이 되겠다.

사람들이 올려준 방법 다 해봐도 안되고 외국인이 영어로 쓴 답변을 번역까지 해가며 난리쳤는데 그대로였다.

오브젝트 레퍼런스가 오브젝트 형태의 인스턴스가 아니라는 뜻이다. 처음에는 뭔 소린지 하나도 모르겠어서 해결 방법도 없고 처음부터 다시 해야하나 생각했었는데, 이것저것 시도해보다가 오류가 사라진 순간 온몸에 전율이..ㅋㅋ

내 경우 이 오류가 두개 떴었는데 원인과 해결방법은 각각

1. Start 함수에서 component를 정의하지 않았다.

animator 변수 선언만 해놓고 component를 가져오지 않아서 생긴 것.

GetComponent<Animator>() 를 해주니 해결됐다.

2. GameObject.Find 에서, 가져올 게임오브젝트가 없으니 찾을 수 없음

다른 스크립트에 사용된 함수를 가져오는 거였는데, 함수를 가져올 게임오브젝트를 만들어놓지 않아서 생긴 것. 만약 함수 이름이 Cat이면 가져와야 할 게임 오브젝트는 cat이라서 헷갈렸다. 대소문자 구분 잘 해야함.

hierarchy 창에 필요한 게임오브젝트를 만들어서 해결했다.

유니티만 엄청 욕했는데 결국 내가 잘못한 게 맞았다😅

NullReferenceException 오류가 뜨는 이유는 어쨌든 내 스크립트에 뭐가 없다는 뜻이니 차근차근 살펴보면서

내가 가져와야 할 컴퍼넌트를 선언했는지, 스크립트에 참조하려고 하는 게임 오브젝트가 제대로 설정이 되어 있는지(대소문자까지 일치!), 혹시 이름에 공백이 포함돼 있진 않은지, 변수 선언을 잘못했는지 등을 꼼꼼히 따져봐야 한다.

저처럼 바보같은 이유로 하루를 날리지 않길 바랍니다😆

#유니티 #유니티2D #유니티오류 #공부 #공부노트 #노트 #코딩 #프로그래밍

A NullReferenceException happens when you try to access a reference variable that isn’t referencing any object. If a reference variable isn’t referencing an object, then it’ll be treated as null. The run-time will tell you that you are trying to access an object, when the variable is null by issuing a NullReferenceException.

Reference variables in c# and JavaScript are similar in concept to pointers in C and C++. Reference types default to null to indicate that they are not referencing any object. Hence, if you try and access the object that is being referenced and there isn’t one, you will get a NullReferenceException.

When you get a NullReferenceException in your code it means that you have forgotten to set a variable before using it. The error message will look something like:

NullReferenceException: Object reference not set to an instance of an object at Example.Start () [0x0000b] in /Unity/projects/nre/Assets/Example.cs:10

This error message says that a NullReferenceException happened on line 10 of the script file Example.cs. Also, the message says that the exception happened inside the Start() function. This makes the Null Reference Exception easy to find and fix. In this example, the code is:

//c# example using UnityEngine; using System.Collections; public class Example : MonoBehaviour { // Use this for initialization void Start () { __GameObject__The fundamental object in Unity scenes, which can represent characters, props, scenery, cameras, waypoints, and more. A GameObject's functionality is defined by the Components attached to it. [More info](class-GameObject.html)<span class="tooltipGlossaryLink">See in [Glossary](Glossary.html#GameObject)</span> go = GameObject.Find("wibble"); Debug.Log(go.name); } }

The code simply looks for a game object called “wibble”. In this example there is no game object with that name, so the Find() function returns null. On the next line (line 9) we use the go variable and try and print out the name of the game object it references. Because we are accessing a game object that doesn’t exist the run-time gives us a NullReferenceException

Null Checks

Although it can be frustrating when this happens it just means the script needs to be more careful. The solution in this simple example is to change the code like this:

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

Now, before we try and do anything with the go variable, we check to see that it is not null. If it is null, then we display a message.

Try/Catch Blocks

Another cause for NullReferenceException is to use a variable that should be initialised in the InspectorA Unity window that displays information about the currently selected GameObject, asset or project settings, allowing you to inspect and edit the values. More info
See in Glossary
. If you forget to do this, then the variable will be null. A different way to deal with NullReferenceException is to use try/catch block. For example, this code:

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

In this code example, the variable called myLight is a Light which should be set in the Inspector window. If this variable is not set, then it will default to null. Attempting to change the color of the light in the try block causes a NullReferenceException which is picked up by the catch block. The catch block displays a message which might be more helpful to artists and game designers, and reminds them to set the light in the inspector.

Summary

  • NullReferenceException happens when your script code tries to use a variable which isn’t set (referencing) and object.
  • The error message that appears tells you a great deal about where in the code the problem happens.
  • NullReferenceException can be avoided by writing code that checks for null before accessing an object, or uses try/catch blocks.

How do you correct an object reference not set to an instance of an object?

How to Avoid Object Reference Not Set to an Instance of an Object?.
Explicitly check for null and ignore null values. ... .
Explicitly check for null and provide a default value. ... .
Explicitly check for null from method calls and throw a custom exception. ... .
Use Debug..

How do I fix this error object reference not set to an instance of an object in unity?

To fix this example we can acquire a reference to an instance of the script using GameObject. Find to find the object it is attached to. We then use GetComponent to find the script component we want a reference to. You can also double click the error to take you to the line of script where the error is occurring.

What does it mean object reference not set to an instance of an object unity?

Well the error "object reference not set to an instance of an object" means that you are trying to access something that is currently empty. To try and fix this first be sure that all of your variables have set values and are not null.

Toplist

Neuester Beitrag

Stichworte