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 /
avatar image
0
Question by Toomuchbob · Jan 10, 2013 at 06:03 AM · nullreferenceexceptionvariables

I fixed a problem in my code, but don't understand WHY it fixed it, explain please.

 #pragma strict
 
 var unitSelected : boolean = false;
 var currentUnit : Transform;
 
 function Start ()
 {
     
 }
 
 function Update ()
 {
     var getCoords : Vector3;
     var hit : RaycastHit;
     var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
     //var currentUnit : Transform;
     
     if(Input.GetMouseButtonDown(0))
     {    
         print(unitSelected + "!!!");
         if(unitSelected == true && Physics.Raycast(ray, hit, 1000))
         {
             getCoords = Vector3(Mathf.Round(hit.point.x), Mathf.Round(hit.point.y), Mathf.Round(hit.point.z));
             currentUnit.position = getCoords;
             unitSelected = false;
         }
         else if(Physics.Raycast(ray, hit, 1000))
         {
             currentUnit = hit.transform;
             //For debugging purposes, the next two lines are staying, but are not being used elsewhere in this script
             getCoords = Vector3(Mathf.Round(hit.point.x), Mathf.Round(hit.point.y), Mathf.Round(hit.point.z));
             print(getCoords);
             
             if(currentUnit != null  && currentUnit.tag == "Player 1")
             {
                 print(currentUnit);
                 unitSelected = true;
             }
         }
     }
 }

In this code, the:

 var currentUnit : Transform;

was previously being declared only in the function Update instead of at the top (what is this called?). You can see where I commented it out there, just after the ray variables were declared. My question is, why when I moved the variables declaration up from the function Update to the top, wasmy NullReferenceException suddenly gone? Previously through debugging I discovered that the currentUnit variable was being set to null right after I clicked on something.

Can anyone please break this down for me? What happens to the variable when it's being declared in function Update that doesn't happen when it's declared at the top?

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

2 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by Eric5h5 · Jan 10, 2013 at 07:41 AM

When a variable is declared outside a function, it's global. If it's inside Update then it's local, and is reset to null every frame because you say "var currentUnit : Transform" without assigning it a value. If it's global, then once it's set to something other than null, it stays set since it's not being re-declared every frame. So your attempt to do "currentUnit.position = getCoords" is using a variable that will always be null (unless it's global).

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
avatar image
0

Answer by $$anonymous$$ · Jan 10, 2013 at 07:46 AM

What most likely happened is this:

The update function is of the course the function which is run by Unity once every frame. When you declare your variable currentUnit in the Update function it becomes a local variable which only resides within this function. This means that at the end of the function, the variable will be pushed out of what is called a stack frame, and it will be unloaded from memory. Then during the next frame, you reinitialize the variable again and so it holds no value whatsoever, and thus becomes a null reference :) Basically, whatever value you set this variable to it would be forgotten after the Update function had finished running once (not sure how you set this value beforehand, but if it was only set once a single time it would be "forgotten" again in the next frame). So if you set the value of the variable only once, it will simply be deleted and then when you reference the variable during the next frame, it would be null because the variable is remade with no value, so to speak.

On the other hand, when you declare a variable outside of any function (it can be the top of your script, but the line location doesn't matter, only if it's outside of a function or not), you are essentially making a "global" scope variable which can be seen by all functions in your script. The important difference here being that when currentUnit is declared outside of any functions, it will exist independently of those functions. This means that when you now set the value of currentUnit that value will simply exist as long as the GameObject which the script is attached to exists, it continues to live and is not influenced by the functions this way.

Hope this helps :)

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

9 People are following this question.

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

Related Questions

How do I switch Canvases? & NullReferenceException (U5) 4 Answers

Variables are assigned but it returns null 2 Answers

Having a very strange problem passing a variable from one script to another 1 Answer

Is there any way to edit variables inside other scripts without declaring them as static? 1 Answer

C# NullReferenceException 1 Answer


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