Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
This post has been wikified, any user with enough reputation can edit it.
avatar image
27
Question by Peter G · Feb 15, 2011 at 08:57 PM · errornullreferenceexceptionscriptingbasicsdebugoafa

What is a Null Reference Exception In Unity.

This question comes up very frequently so I decided I would create a general explanation of what a Null Reference Exception is. This isn't so much for me as it is for beginners and others new to programming or Unity.

Because the biggest problem appears to be that people new to programming or .Net don't understand what a NullReferenceException means, and it really isn't too hard to fix if you know what your looking for.

So, I'll be posting my explanation. If anyone else has a good explanation, then please post so that there can be one catch-all question for NullReferenceExceptions.

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

3 Replies

· Add your reply
  • Sort: 
avatar image
29
Best Answer Wiki

Answer by Peter G · Feb 15, 2011 at 08:59 PM

NullReferenceException are thrown when you try to access a reference variable that isnt referencing any object, hence it is null. So the first question, are all variables reference types?

No, in Mono, there are two kinds of variables that are used for most variables: value types and reference types. Value types store a value directly such as an int or a double or any struct such as a Vector3, or an enumeration.

Reference types, on the other hand to not directly store the object data, instead, they store a reference to an object similar to pointers in C/C++. Common reference types are classes, delegates, and strings. Reference types default to null, that is that they are not referencing any object. Hence, if you try and access the object that is being referenced and their isnt one, you will get a NullReferenceException.

Here is another Answer about null references that explains the same thing in slightly different words.

Some common examples:

 var t : Transform; 
 //t is a reference to a Transform.
 //If you do not assign a Transform to it in the Inspector, then
 //it will be be a null reference..
 
 function Start () {
      t.Translate();
      //If t does not have a Transform, then you will get a NullReferenceException
 }

If you try to get a component that isnt there then try to access it:

 function Start () {
       var c : Light = GetComponent(Light);
 
      c.range = 10;
      //If this object doesnt have a light on it, then you will get
      //a NullReferenceException
 }

Accessing a GameObject that doesnt exist:

 function Start () {
     var someGameObject : GameObject = GameObject.Find("AGameObjectThatDoesntExist");
 
     someGameObject.name = "NullReferenceException";
 }


Less common, but annoying if you don't know it:

 //Note this example is C#. There is no good way of doing delegates in js
 public void NullDelegate (MyEmptyDelegate del) {
      del();
      //if you call a delegate that doesn't have any methods attached, you will get a NullReference Exception.
 }

Fixes

Now to how to fix them: obviously the easiest way to fix them is to not have any NullReferences. But many times thats not possible so you need to have either try-catch blocks or conditionals.

For example:

 var c = GetComponent(MyComponent);
 
 if(c != null) {
     //Make sure we have a reference.
     //Do the rest of the stuff.
 }
 
 else {
     Debug.Log(There is no MyComponent attached to this object);
 }

or:

 try {
      //execute code;
 }
 
 catch (var ex : NullReferenceException) {
       //Do other stuff.
 }

try/catch blocks require that you throw an exception and that does cost resources so more often than not, even though it is sometimes cleaner to read, it isn't as performance efficient.

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image ScorpyX · Oct 23, 2013 at 01:28 AM 0
Share

Awesome explanation! Thank you it help me to undarstand core of my probleme

avatar image KEMBL · Jun 26, 2015 at 11:30 PM 0
Share

Great! And one more approach available:\

   if(object.ReferenceEquals(someValue,null))
   {
    //someValue is null
   }
Note! Probable this code will work buggy on non PC platforms (at least on Android).

avatar image
4

Answer by Kiwasi · Jan 04, 2015 at 11:27 PM

In simple terms:

A null reference error means something before a dot is null.

To Fix

  • Find the line from the error code

  • Find the dot

  • Figure out what is null. Debug.Log is your friend

  • Make it not null, or add null checking before hand

(Note: this answer is not technically correct, but it is a pretty good working solution for 99% of beginner null reference exceptions. If you can write a delegate, you can read the documentation and identify your own null references)

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image BiteOf87 · Mar 05, 2017 at 11:13 PM 0
Share

I don't really want to do this answer because for some reason it's giving me an NRE at C:/buildslave/unity/build/Editor/$$anonymous$$ono/$$anonymous$$odules/$$anonymous$$odule$$anonymous$$anager.cs. Don't know why Unity's own script is generating errors.

avatar image
1

Answer by Ephora · Oct 27, 2015 at 03:17 PM

Also, if you try to reference a script with its name as it is shown in the Inspector, sometimes you'll get a Null Reference Exception. If that's the case, just verify if the name of your actual script is the same.

(For example, "EnemyScript" would be shown as "Enemy Script" with a space in the inspector. If you tried to access it with

 myObject.GetComponent ("Enemy Script");

you would get that error. Instead, you should write

 myObject.GetComponent ("EnemyScript");


I'm a beginner, and I learned the hard way, verifying all my scripts and Debugging when it was just the name that had no space.

So I hope this will help other beginners too !

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

16 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Script error about the semicolon. 1 Answer

Im getting a "NullReferenceException: Object reference not set to an instance of an object" error not sure why. 1 Answer

Raycast from the wrong position. 1 Answer

NullReferenceException... 1 Answer

Simple C# problem 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges