Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 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 /
  • Help Room /
avatar image
0
Question by shapirog · May 11, 2016 at 02:03 AM · error messagenullreferenceexceptionarraysfindgameobjectswithtag

NullReferenceException randomly occurs

Hello, I am pretty new to Unity and am running into something that I can't figure out.

There are a few parts of my code that randomly causes a NullReferenceException. They all involve using FindGameObjectsWithTag and then running a for loop through the array and doing something. For example:

 landedPlatformNumber = collision.gameObject.GetComponent<PlatformController> ().platformNumber;
         GameObject[] platforms = GameObject.FindGameObjectsWithTag ("Platform");
         for (var i = 0; i < platforms.Length; i++) {
             if (platforms [i].GetComponent<PlatformController> ().platformNumber < landedPlatformNumber) {
                 platforms [i].GetComponent<PlatformController> ().DropPlatform ();
             }
         }

What is happening is the player is jumping up off a platform onto a higher platform. When the player lands on a platform the game removes the platforms below the one you landed on. This bit of code is called when you land on a platform. The script is part of the player gameobject.

The thing is, this normally works perfectly. But every now and then, for no reason that I can figure out (even when I haven't changed the code at all) I get the NullReferenceException. The frustrating thing is that while I try to figure out what the problem is, it will randomly fix itself and the errors no longer show up. Or I can restart unity and then it works again, even though I don't change anything in the code!

Please let me know if there is a something that I can do to fix this - I assume there's something obvious in my code that is incorrect or I am using something in the wrong way.

Thank you!

Comment
Add comment · Show 4
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 UsmanAbbasi · May 11, 2016 at 06:31 AM 0
Share

Show the null reference error you get.

avatar image shapirog UsmanAbbasi · May 12, 2016 at 02:27 AM 0
Share

NullReferenceException: Object reference not set to an instance of an object at PlayerController.OnCollisionEnter (UnityEngine.Collision collision) [0x000a9]

avatar image UsmanAbbasi shapirog · May 12, 2016 at 05:53 AM 0
Share

This is not the complete error message. Complete error message will also show the line number which is causing the null reference error. And also post the complete method in which error is occurring.

Show more comments

2 Replies

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

Answer by Naphier · May 13, 2016 at 06:33 AM

I imagine it's in here:

 landedPlatformNumber = collision.gameObject.GetComponent<PlatformController> ().platformNumber;
          GameObject[] platforms = GameObject.FindGameObjectsWithTag ("Platform");
              for (var i = 0; i < platforms.Length; i++) {
                  if (platforms [i].GetComponent<PlatformController> ().platformNumber < landedPlatformNumber) {
                      platforms [i].GetComponent<PlatformController> ().DropPlatform ();
                  }
              }


There's a lot of improvement and null checking that should be done like so:

 PlatforController pc = collision.gameObject.GetComponent<PlatformController> ();
 if (pc != null)
 {
     landedPlatformNumber = pc.platformNumber;
     GameObject[] platforms = GameObject.FindGameObjectsWithTag ("Platform");

     for (var i = 0; i < platforms.Length; i++) 
     {
         PlaformController pc2 = platforms [i].GetComponent<PlatformController> ();
         if (pc2 == null)
             continue;

         if (pc2.platformNumber < landedPlatformNumber) 
         {
             pc2.DropPlatform ();
         }
     }
 }

A few notes:

  • When using GetComponent always check that the component isn't null before accessing its members.

  • Do everything you can to reduce calls to GetComponent because it is slow.

  • Similarly reduce calls to Find methods because they are slow too.

  • It would be better that this script is able to reference a List of PlatformControllers that have been created. That way you can check if collision.gameObject = platformControllerList[i].gameObject and also use that List to iterate through without the need of all these Find and GetComponent calls. Still check for nulls though before accessing members!

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 shapirog · May 14, 2016 at 01:29 AM

Thank you so much for this helpful response. I really appreciate you taking the time to give such constructive advice. I will take note of your points and apply them to the rest of my code as well!

Out of curiosity, is there a reason why Unity would produce this error only sometimes?

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 Naphier · May 14, 2016 at 02:35 AM 0
Share

Yes, because only sometimes you've deleted a gameobject. So it's to your best advantage to try to figure out these unexpected things (trace them out) then see if they are truly unexpected.

avatar image shapirog Naphier · May 14, 2016 at 02:36 AM 0
Share

Got it. Thanks again for your help.

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

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

Related Questions

Need Help Fixing NullReferenceException in Text Adventure Game 0 Answers

C# ArrayList Accessing and RemoveAt? 0 Answers

Keep Getting NullReferenceException: Object reference not set to an instance of an object 0 Answers

ML Agents Null Pointer error 0 Answers

javascript NullReferenceException: Object reference not set to an instance of an object 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