• 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 MerlinsMaster · Sep 09, 2016 at 03:16 AM · nullreferenceexceptionvariablespassing

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

Hey Guys,

I have two C# scripts, InstanceTest.cs and TargetScript.cs, which are both attached to the same gameobject, TestManager.

In InstanceTest, I created a handle to TargetScript. In TargetScript, I have a public int called testVariable. The issue I am having is when I try to display the value of testVariable from the InstanceTest script.

It works fine in the Start function, but in the Update function, I keep getting a nullReferenceException error.

I can't for the life of me figure out why it is working in one function and not the other. Once I create the handle, I should have continuing access.

Here are the two scripts:

 using UnityEngine;
 using System.Collections;
 
 public class InstanceTest : MonoBehaviour {
 
     public TargetScript ref_TargetScript;
  
     void Start()
     {
         // get access to the TargetScript script on the same gameobject
         TargetScript ref_TargetScript = GetComponent<TargetScript>();
 
         Debug.Log(ref_TargetScript.testVariable);
     }
 
     void Update()
     {
         Debug.Log(ref_TargetScript.testVariable);
     }
 }

and

 using UnityEngine;
 using System.Collections;
 
 public class TargetScript : MonoBehaviour {
 
     public int testVariable = 5;
 }


Thanks in advance.

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

1 Reply

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by Addyarb · Sep 09, 2016 at 03:21 AM

Hi there,

So in the start function, you are redeclaring your ref_TargetScript variable. Another way to phrase this, is that you are declaring a temporary variable. What you really want to do is set your already declared ref_TargetScript variable.

Think of it this way: When you write 'TargetScript' in front of your variable on line 12, you're telling Unity: "Hey, I have a brand new variable that I want to keep track of, but only until the end of this Start function."

If Unity could reply, it might say: "Great! Oh wait.. It looks like you've already named a variable the same exact thing, but since it's not in this method, and since you put the variable type right infront of it you must want a whole different reference!"

However, if you set your already declared variable by simply typing your variable name with an = next to it, you're telling unity "What I'm about to tell you is what I'd like you to set the above variable to, and I'd like you to hold on to that reference indefinitely."

In other words, remove 'TargetScript' from line 12 - and your scripts will behave as expected.

     public class MyClass : MonoBehaviour
     {
         //This is where we reference our 'other' class.
         public MyOtherClass otherClass;
 
         void Start()
         {
             //Contrary to what you may think, the declaration below is NOT setting the above reference.
             //This is actually creating a temporary reference which will be destroyed
             //at the end of this start function. 
             //Even if it shares the same exact name, it is in a different SCOPE, 
             //The scope of this temporary variable is only within this method.
             MyOtherClass otherClass = FindObjectOfType<MyOtherClass>(); 
 
             //Here is how to properly set our above reference:
             otherClass = FindObjectOfType<MyOtherClass>();
 
             //Notice that we don't redefine our type. We have already defined it above,
             //and a redefinition of the class means that said reference will only exist
             //for this method.
         }
     }
 }




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 MerlinsMaster · Sep 09, 2016 at 03:35 AM 0
Share

Thanks a lot. I thought I was going crazy for a while there. It's my first time trying to access a script from the same gameobject, as opposed to another gameobject.

avatar image Addyarb MerlinsMaster · Sep 09, 2016 at 03:44 AM 0
Share

Happy to help! It's not an easy thing to grasp right away - especially when the compiler doesn't have any issue with you na$$anonymous$$g a temporary variable the same thing as a global variable. That's just kind of how it works, though.

Fortunately, you have the very correct approach of capturing the reference to your script in the Start function - ins$$anonymous$$d of trying to reference it every frame in the Update function. Once you get past the little quirks like this, things become very easy.

Good luck with your future coding adventure!

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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

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

Related Questions

Passing variables back and forth in client server environment using RPC 1 Answer

Variables are assigned but it returns null 2 Answers

Can't read variables from another script ? 0 Answers

Child not accepting variables from the parent 0 Answers

Quick question about performance 0 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