• 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 /
  • Help Room /
avatar image
Question by calebaker · Aug 27, 2015 at 08:28 PM · inspectorgameobject.findgamobject

How to properly reference a game object

If I attempt to assign a GameObject to a private variable in Start() or Awake() then access that object I get NullReferenceException.

But if I make it public and assign it via inspector it works fine. What am I doing wrong?


This works if drag and drop the game object into myObject via the inspector.

 using UnityEngine;
 using System.Collections;
 
 
 public class ChangeControls : MonoBehaviour {
 public GameObject myObject;
     
     void ChangeMyObject()
     {
         myObject.SomeValue = 42;
     }   
 }

This however does not work.

  using UnityEngine;
  using System.Collections;
  
  
  public class ChangeControls : MonoBehaviour {
  private GameObject myObject;
      void Start()
     {
         myObject = GameObject.Find("My Object");
     }
      void ChangeMyObject()
      {
          myObject.SomeValue = 42;
      }   
  }
Comment

People who like this

0 Show 2
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 Dave-Carlile · Aug 27, 2015 at 08:29 PM 1
Share

I assume by GetObject.Find you mean GameObject.Find?

Do you have an object in your hierarchy named My Object? Is it active/enabled?

avatar image calebaker · Aug 28, 2015 at 01:32 PM 0
Share

My apologies, you are correct. I fixed it. And yes there is an object called "My Object" and it is active/enabled.

3 Replies

· Add your reply
  • Sort: 
avatar image
Best Answer

Answer by calebaker · Aug 28, 2015 at 08:29 PM

I ended up scrapping the script and created a new one from scratch and now it works.

The only thing I can come up with is something (a reference) had to be corrupted in Unity because the new script exactly matches the old one.

Comment

People who like this

0 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 Mako-Infused · Aug 28, 2015 at 10:13 PM 0
Share

@calebaker That's odd, but it would make the most sense being that all of the likely certainties were ruled out! I even reproduced your setup earlier today and found no issues getting the code to work as intended.

avatar image

Answer by Mako-Infused · Aug 27, 2015 at 08:34 PM

There's a chance that the line:

 myObject = GameObject.Find("My Object");

Is not finding the object. In which case it would be null, of course that can be prevented by using a null check when assigning values.

Additionally, I would try moving your find of the object into an "Awake" method instead of "Start". This is necessary if your "ChangeMyObject()" method is being invoked before the value is assigned.

Comment

People who like this

0 Show 4 · 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 calebaker · Aug 28, 2015 at 01:39 PM 0
Share

As mentioned in my original post, I have attempted Awake() but I get the same result.

I don't believe proper prevention of an error is to just not do the thing that would cause the error in the first place but instead to do it correctly by fixing what caused the error.

avatar image Landern · Aug 28, 2015 at 01:56 PM 0
Share

Awake is called on all objects first before Start, Execution Order from the docs. If you put it in the Awake function you have no guarantee(with out modifications) that the object has been initialized. Where as in the Start method you know Awake was called on everything in the scene that can have it called. The Start method is more appropriate.

avatar image Mako-Infused · Aug 28, 2015 at 02:09 PM 0
Share

My apologies, I didn't realize that you mentioned using Start and Awake. Awake should definitely be the more correct implementation, considering that you're linking an object to a variable.

I didn't mean to imply that it would prevent the error, rather that you should really consider adding in a null check when working with "GameObject.Find" since names aren't static. As a bonus this approach might also help you debug the problem yourself. However, it really depends on your implementation.

The problem is definitely that the component doesn't exist at the time "ChangeMyObject" is called, which narrows down the possible reasons for that to: the name is wrong, or the timing is wrong. The only other possible reason for the issue might be due to the "SomeValue" not referencing the component which contains that value, in which case a cast might be needed.

avatar image calebaker · Aug 28, 2015 at 02:23 PM 0
Share

@Mako

No worries, the idea of a null check is a solid one. I attempted once again to place it in Awake but I'm getting the same result. I have verified and had a coworker verify that the naming is correct.

I'm wondering now if something has gotten corrupted in the scene/unity editor?

Remember to keep in mind that when this object is assigned in the inspector I am able to modify SomeValue.

avatar image

Answer by Barachiel · Aug 28, 2015 at 03:38 PM

Quickly testing this out, using this script:

 using UnityEngine;
 using System.Collections;
 
 
 public class ChangeControls : MonoBehaviour
 {
     private GameObject myObject;
 
     void Start()
     {
         myObject = GameObject.Find("My Object");
 
         if(myObject != null)
         {
             ChangeMyObject();
         }
     }
 
     void ChangeMyObject()
     {
         Debug.Log("Found!");
     }
 }

No errors are returned and it works fine. This suggests that it's something else in your script, perhaps 'myObject.SomeValue'.

Since it works fine if you assign it via inspector, perhaps you could explain more about what this value is, since in the code provided it makes no sense.

Comment

People who like this

0 Show 0 · 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.

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

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

Related Questions

How do I fill a Sprite[] in the alphabetical order in the script Inspector? 1 Answer

Control an image fill, using another slider, via the inspector 0 Answers

Prefabs not working, can't find Prefabs folder 0 Answers

Serialize inherited List class, to display in Inspector 0 Answers

How to create new line in string from inspector? 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