• 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.

Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.



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

Why is my destroy platform script now working? NullReferenceException: Object reference not set to an instance of an object. 1 Answer

NullReferencException on Int array 2 Answers

JS NullReferenceException: Object reference not set to an instance of an object 1 Answer

Array of dictionaries: "Object reference not set to an instance of an object" 0 Answers

Object reference not set to an instance of an object [HELP!] 0 Answers

  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges