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 NornIndustries · Aug 05, 2014 at 05:47 PM · nullreferenceexceptionarrays

NullReferenceException happens only sometimes without cause?

I have two scripts in my game which cycle through objects and do stuff with them (if they exist). The problem is that I've noticed some very strange and frustratingly inconsistent behaviour with array references.

Take the following, which finds the player's base and returns them to it. Sometimes it works, sometimes it doesn't. To my knowledge nothing important changes to cause it to success or fail, it just does that on a whim.

         // find home button
         if (Input.GetKeyDown(KeyCode.H))
         {
             GameObject[] home;
             home = GameObject.FindGameObjectsWithTag("building");
             GameObject goTo = gameObject;
             
             for (int i = 0; i < home.Length; i++)
             {
                 if (home[i].GetComponent<Building>().unitMaster == gameObject)
                 {
                     goTo = home[i];
                 }
             }
             
             if (goTo != gameObject)
             {
                 GameObject camera = Camera.main.gameObject;
                 camera.transform.position = new Vector3(goTo.transform.position.x-14, goTo.transform.position.y+28, goTo.transform.position.z-14);
             }
         }

The other example suffers the same problem, the error is sometimes thrown that no instance exists when clearly the objects that it is searching for do exist with the right tag etc. What I found even more baffling is that without the Debug.Log prior which refers to the array length it will fail. Otherwise, with the Debug left in, it works. I don't understand that in the slightest.

 void Grow2()
 {
     GameObject[] mushrooms = GameObject.FindGameObjectsWithTag("mushroom");

     for (int i = 0; i < mushrooms.Length; i++)
     {
         // For some bizarre reason it will throw an error about mushrooms[i] not being an instance without this!
         Debug.Log ("mushrooms.Length "+mushrooms.Length);

         if (mushrooms[i].GetComponent<Mushroom>().height == 2)
         {
             // mushroom must be able to grow
             if (mushrooms[i].GetComponent<Mushroom>().transform.localScale.x < mushrooms[i].GetComponent<Mushroom>().stopSize)
             {
             // check for collision with non-tile objects (this will stop growth!)
             Collider [] colliders = Physics.OverlapSphere(mushrooms[i].transform.position, mushrooms[i].GetComponent<Mushroom>().growFloat * 0.8f);

             for(int j = 0; j < colliders.Length; j++)
             {
                 if (colliders[j].tag != "tile" && colliders[j].tag != "unit" && colliders[j].gameObject != mushrooms[i])
                 {
                     mushrooms[i].GetComponent<Mushroom>().stopSize = mushrooms[i].GetComponent<Mushroom>().growFloat;
                 }
             }

             // grow mushroom
             if (mushrooms[i].GetComponent<Mushroom>().transform.localScale.x < mushrooms[i].GetComponent<Mushroom>().stopSize)
             {
                 mushrooms[i].GetComponent<Mushroom>().growScale.x += 0.1f;
                 mushrooms[i].GetComponent<Mushroom>().growScale.y += 0.1f;
                 mushrooms[i].GetComponent<Mushroom>().growScale.z += 0.1f;
                 mushrooms[i].GetComponent<Mushroom>().growFloat += 0.1f;
                 mushrooms[i].GetComponent<Mushroom>().transform.localScale = mushrooms[i].GetComponent<Mushroom>().growScale;
             }
             }
         }
     }
 }

I'm at a loss, I don't understand what the problem is since the error seems to happen quite randomly sometimes, and then other times it works without flaw. What could be the cause of the problem?

Comment
Add comment · 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 meat5000 ♦ · Aug 05, 2014 at 05:54 PM 0
Share

Debug.Logs are terrible in for loops.

This is because the loop executes much faster than the Debug.Log can keep up, so you only every seem to get the final value and not constant updating values.

avatar image JoshPeterson · Aug 05, 2014 at 06:04 PM 2
Share

Can you provide the specific text and call stack from the NullReferenceException when it occurs?

2 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by tanoshimi · Aug 05, 2014 at 05:59 PM

The only logical explanation of the first error you describe (assuming you've definitely pasted the correct block of code) is either:

  • There is an object tagged as "building" that does not have a Building script component attached to it.

  • There is an object tagged as "building" with a Building script component that contains an unassigned/null unitMaster variable

That's it. So you need to step through your code and check where either of those situations could occur.

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 NornIndustries · Aug 05, 2014 at 07:03 PM 0
Share

Didn't modify either code blocks, built the game and ran a multiplayer test; and both things worked during that test, and then when I playtested singleplayer after.

Not really considering this solved since I still have yet to isolate what caused the fault to occur or be fixed in the first place.

avatar image
0

Answer by NornIndustries · Aug 11, 2014 at 11:28 PM

So after some testing I have determined that, for reasons I do not understand, sometimes the editor's playtest fails to read arrays. This however is always fixed if I build and run a multiplayer test. I've never seen the error happen in a built version of the game, so I don't know what's causing the issue, but thankfully it isn't crippling.

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 rutter · Aug 11, 2014 at 11:30 PM 1
Share

Sounds like classic shotgun debugging.

NullReferenceExceptions don't just pop up for no reason. You might have a subtle race condition or some other problem, but there definitely is a problem.

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

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

Multidimensional GameObject Arrays 1 Answer

Null reference when accessing GameObject in the Array(C#) 1 Answer

Split() into a fixed length array? 1 Answer

Access System.Serializable class from script? 1 Answer

MergeSort function acting strange 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