• 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 lachesis · Sep 17, 2013 at 09:21 PM · nullreferenceexceptioncastingforloop

Null reference exception with elusive cause

I'm attempting to run a UnityScript script with which I see no apparent problems. However, when I attempt to run the scene in which the script below is embedded, it throws a NullReference exception on Line 26.

 #pragma strict
 
 // Inspector variables
 
 var triBall : GameObject;
 var detector : GameObject;
 var floorDistance : float;
 var incrementCount : int = 10;
 var incrementSize : float;
 
 // Private variables
 
 private var lowestActive : Vector3;
 
 function Update () {
     if(Input.GetKeyDown("space")){
         
         // Instantiate a tri-ball and store its childrens' Transform components in an array
         
         var activeTriBall : GameObject = Instantiate(triBall, transform.position, Quaternion.identity);
         
         var childBalls : Transform[] = activeTriBall.GetComponentsInChildren(Transform);
         
         // Find the position, in Vector3, of the child ball with the least y position and store that in lowestActive
         
         for (var pos : Transform in childBalls){
             if(floorDistance == null || pos.position.y < floorDistance){
                 floorDistance = pos.position.y;
             }
         }

 // Calculations used to prepare and pass a variable to another script. Probably irrelevant to the question but included in case there's some connection that I can't see.

         incrementSize = floorDistance / incrementCount;
         activeTriBall.GetComponent(TriBallControl).stepRate = incrementSize;
         
         var activeDetector : GameObject = Instantiate(detector, transform.position - Vector3(0,.5,0), Quaternion.identity);
         activeDetector.transform.parent = activeTriBall.transform;
     }
 }

Some context:

  • triBall is a prefab with three spherical children

  • detector is a duplicate of the triBall with renderers removed (but colliders active and set to non-kinematic) that rides in front of the triBall's path to detect collisions early.

The script's purpose is straightforward: I embed a keypress listener in an Update() function within a script attached to an empty GameObject titled SpawnPoint. When the player presses space, the script instantiates a prefab named "tri-ball" at the SpawnPoint's position and stores the tri-ball in variable activeTriBall.

Once the tri-ball has been instantiated and a reference established, I declare a Transform array--childBalls--and store the Transform components of each of the three spherical child objects. I then run a for loop on each of the Transform components stored in the childBalls array to determine the lowest position.y in the array.

I use this position.y (floorDistance) to run a calculation for another script in my scene. The code likely isn't relevant to my problem, but I've included it here for clarity.

The debug process identifies Line 26 as the source of the NullReference exception:

 for(var pos : Transform in childBalls) 

However, given that I've already instantiated childBalls, I don't see why this is so. Does anyone know why?

Comment
Add comment · Show 1
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 Hoeloe · Sep 17, 2013 at 11:35 PM 1
Share

foreach is a C# thing if memory serves, so it's right here. Also, floorDistance not being initialised is in theory correct, but lachesis should keep in $$anonymous$$d that primitive types, like float, do not have a concept of "null" (though floats do have a concept of NaN, but this is not the same). Ins$$anonymous$$d, when you create a float and don't assign it, it will be assigned to 0. If you were using C#, you could use the nullable operator to box the float, allowing it to be assigned to null (by defining the type as float? rather than just float). There may be an alternative in UnityScript, but I am not as familiar with it - it may be worth looking up nullable types though.

Despite this, the only thing that could cause line 26 to throw that exception is if childBalls is null. This means that you GetComponent call is returning no components. This may be because your object has no children, it's worth double checking that.

1 Reply

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

Answer by lachesis · Sep 18, 2013 at 12:31 AM

Solved! I was using the outdated (hopefully deprecated) version of GetComponentsInChildren.

The vanilla GetComponentsInChildren() returns an array of Component types. I was attempting to use this, then cast the array as a different type within the same statement. It appears that this is impossible:

http://forum.unity3d.com/threads/27026-Help-with-GetComponentsInChildren

An alternative would've been to store the output from GetComponentsInChildren(), then cast each of its separate members as a Transform within a for loop:

http://answers.unity3d.com/questions/215597/why-cant-i-create-the-getcomponentsinchildrenrende.html

Instead, I used the generic version of GetComponentsInChildren(), which returns an array of the specified component type:

http://docs.unity3d.com/Documentation/Manual/GenericFunctions.html

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

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

17 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

Related Questions

Roguelike2d example Walls fail to cast correctly in Player:OnCantMove 2 Answers

NullReferenceException? 2 Answers

Null Reference Expantion 1 Answer

Null Reference Exception For Blocks C# 1 Answer

No idea what happend to unity (See pictures) 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