• 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
1
Question by Defective02 · Feb 04, 2015 at 07:06 AM · c#getcomponent

c# GetComponent strange behaviour

Hello everyone :)

I recently got a little problem with the behaviour of the GetComponent method that it's driving me crazy because it seems quite.. random, and can't figure out the problem.

I have a character with a control script attached, and i'm trying to call it in other scripts to have it referenced (instead of making the variable public and adding it in the inspector)

 private Mob player;
 
     public void Awake() {
         player = GameObject.FindGameObjectWithTag("Player").GetComponent<Mob>();
     }

This way i would have the script that it's going to be used to get some of the methods. I have the character tagged as 'Player' and attached to it the script named (to be original with it) 'Player' that extends 'Mob'.

This works.. kinda. The first time that i run unit and start running the scene it doesn't fail and do what it's supposed to do, all right there, but when i stop it and restart, there are times in which it works again and other times in which it throws an error 'NullReferenceException' highlighting the code where the variable is called, for example

 public void Update() {
      if(player.getCurrentEnergy() < spell.getCost()) {}
 }

This line throws error. I've went into double checking the script, and it's still there, not deleted by mistake: alt text

I've checked if it could be the 'Player' tag

     if(GameObject.FindGameObjectWithTag("Player") != null) {
             Debug.Log("Player: " + GameObject.FindGameObjectWithTag("Player"));
             if(GameObject.FindGameObjectWithTag("Player").GetComponent<Mob>()) != null) {
                 Debug.Log("Component: " + GameObject.FindGameObjectWithTag("Player").GetComponent<Mob>());
             } else {
                 Debug.Log("Component NULL");
             }
         } else {
             Debug.Log("Player NULL");
         }

alt text

Changing tags or names doesn't seem to help.

What drives me crazy is the randomness of it, it sometimes happen after a pair of runs and other at the second one (the first oppening always runs properly), and it happens more when i start playing the the transitions of the animator (don't know if it's relevant). Once happened it does not recover :o

Did someone faced the problem before? How can i solve it, and over all, why does this happen? O-o

Than you ^-^

script.jpg (71.2 kB)
warning.jpg (8.6 kB)
Comment
Add comment · Show 6
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 GameVortex · Feb 04, 2015 at 07:44 AM 1
Share

Just an idea: In the debug screenshot it prints out the name of the player object: Player(Clone). In the Hierarchy screenshot it shows a Player Prefab already in the scene which will not be named Player(Clone) when playing. Objects will only be named clone if they are instantiated. Are you instantiating any other objects named Player which also have the tag "Player"?

avatar image Defective02 · Feb 04, 2015 at 12:56 PM 0
Share

I've checked the scripts for any instantiate code , ad i don't have any for the player :( and i've disabled every object from the scene other than the player and plane, and left the basic code. Despite of this, the game seems to be indeed instantiating objects by it's own with each run, i mean.. i added

 foreach(GameObject ob in GameObject.FindGameObjectsWithTag("Player")) {
             Debug.Log (ob.transform.position + "   " + ob.transform.root.GetComponent<$$anonymous$$ob>());
         }
         Debug.Log (gameObject.tag + "   " + GameObject.FindGameObjectsWithTag("Player").Length);

in the player Start method to check it up, and each time that i run the game, there is a new Player(Clone) object at the (0.0, 0.0, 0.0) position (which don't appear in the hierarchy neither), and the length increases in one, though the real player is count between them alt text

The steps that i follow to trigger this are, selecting the player, going into animator, running game, removing transition conditions, readding transition conditions, stopping, start :/

warning.jpg (10.5 kB)
avatar image GameVortex · Feb 04, 2015 at 01:09 PM 0
Share

When using Debug.Log you can provide a object. Then when clicking on the debug log in the console the object provided is highlighted. So do that to see which object also has the "Player" tag.

 foreach(GameObject ob in GameObject.FindGameObjectsWithTag("Player")) 
 {
     Debug.Log (ob.name, ob);
 }
 

avatar image Defective02 · Feb 04, 2015 at 01:20 PM 0
Share

Oh :o didn't know that, thank you for the advice ^-^

Added the ob to the debug line, and in the log, when i click over the one with normal cordinates (real player) the hierarchy highlights it, but when i press on any of the others (the zero ones) no object is highlighted :/ alt text

(Lack of null errors is because all the relative code is commented :/ )

warning.jpg (82.7 kB)
avatar image GameVortex · Feb 04, 2015 at 01:25 PM 1
Share

Very interesting. They are either set to be hidden (doubtful) or they are destroyed after awake. I see you have a Spawner object in your player, what does that do?

You could always try to use the FindObjectOfType ins$$anonymous$$d of by Tag. Which will always grab the correct type if it exists:

 $$anonymous$$ob player = FindObjectOfType<$$anonymous$$ob>();
Show more comments

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by AndresBarrera · Feb 04, 2015 at 08:39 AM

As GameVortex said, check that you are not creating duplicates of the Player object. Or, if you are only instantiating one, maybe it is being created after some other Awake functions already looked and failed to find it. The order in which scene objects execute their Awakes is not guaranteed to be always the same. Try instantiating on Awakes and doing the search on Starts.

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 Defective02 · Feb 04, 2015 at 01:04 PM 0
Share

Tried to switch the calls from Awake to Start, but it doesn't make any difference :( From the API it sais

Awake is called after all objects are initialized so you can safely speak to other objects or query them using eg. GameObject.FindWithTag

So i assumed it was safe, don't know :<

The game still keeps creating players one after another with each run, at the (0.0, 0.0, 0.0) position, but also keeping the true one. I have all the code commented except for the debugging one :< I searched for any instantiate method and, despite i have for other pourposes, i don't have any for the player, the player itself it's just a prefab dropped into scene :o

avatar image Bonfire-Boy · Feb 04, 2015 at 02:22 PM 0
Share

The very next sentence in the API is

Each GameObject's Awake is called in a random order between objects. Because of this, you should use Awake to set up references between scripts, and use Start to pass any information back and forth.

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

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

script with individual function for each gameObject or public script variable to solve inventory system problem 1 Answer

How to update UI image mid-game (Unity, C#) 2 Answers

Getcomponent unity 4b11 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