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 MDurkin · Oct 01, 2013 at 01:29 PM · c#errorlistnull reference

Null reference exception: Object reference not set to an instance of an object

I'm very new to Unity. Every other case of this problem I've seen has occurred because they have forgotten to instantiate a new list, but I think I've done that okay... I keep getting the aforementioned error at the line indicated with comment. Any ideas why? My goal is to spawn blocks and have them be automatically destroyed once they fall a certain distance. Thanks in advance.

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 
 public class SpawnBox : MonoBehaviour {
 
     public Rigidbody SpawnedBox;
     static List<GameObject> SpawnedBoxList;
 
     void Start () 
     {
         SpawnedBoxList = new List<GameObject>();
     }
 
     void Update () 
     {
 
         if (Input.GetButtonDown("Jump")) 
         {
             GameObject instanceBox = Instantiate(SpawnedBox, transform.position, transform.rotation) as GameObject;
             SpawnedBoxList.Add((GameObject)instanceBox.gameObject); //NULL REFERENCE EXCEPTION HERE
         }
         
 
         //for (int i = 0; i < SpawnedBoxList.Count; ++i)
         //{
         //    if (SpawnedBoxList[i].gameObject.transform.position.y < -100)
         //    {
         //        Destroy(SpawnedBoxList[i].gameObject);
         //    }
         //}
     }
 }
Comment
Add comment
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

3 Replies

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

Answer by vexe · Oct 01, 2013 at 01:41 PM

All null ref problems in the world could be solved EASILY with debugging.

PLEASE LEARN HOW TO DEBUG YOUR PROGRAM! (If you're on MonoDev, or VS)

Either your box instance is null, and you're adding a null to your list, or your list is null, you just gotta know what's happening to narrow it down. If you want to manually debug it, here's what you could do to nail it:

put a couple of logs at the right places:

 if (Input.GetButtonDown("Jump"))
 {
    GameObject instanceBox = Instantiate(SpawnedBox, transform.position, transform.rotation) as GameObject;
    if (instanceBox == null) {
       Debug.Log("instanceBox is null, problem instantiating");
       return;
    }
 
    if (SpawnedBoxList == null) {
       Debug.Log("list is null, initialize it properly, or something...");
       return;
    }
    SpawnedBoxList.Add((GameObject)instanceBox.gameObject);
 }


You don't need to cast your instanceBox to a GameObject because it already is, and you certainly don't need to take the gameObject component from it (it would return itself) :) (that might have been causing your problem?) - Just do:

 SpawnedBoxList.Add(instanceBox);

Another thing, when you use a static variable, and have the chance to immediately give it a value the moment you initialize it, do it, like:

 static List < GameObject > SpawnedBoxList = new List < GameObject > ();

If you're just beginning, you might wanna be careful with statics, see this for proper use of them (skip to the 'good coding habits' part of the answer) - Do you really need to use a static? I'm sure you could get away without it :)

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 MDurkin · Oct 01, 2013 at 02:09 PM 0
Share

Thank you for your detailed answer, it's much appreciated. I'm not a very experienced coder so your guide on statics was also very helpful.

avatar image vexe · Oct 01, 2013 at 02:11 PM 0
Share

Glad that was all of help. I highly recommend you spend some time and learn how to debug your games/programs (how to use a debugger), it will save you a lot of headaches (and will be a source of headaches as you will discover really strange bugs) - As your games gets bigger and bigger, you can't really go that far without debugging. (Check out the links I added to my answer)

Good luck :)

avatar image
1

Answer by AjayKhara · Oct 01, 2013 at 01:38 PM

Why have you declared the list static ?

Replace those two line with this, And do not forget to assign the SpawnBox rigidbody in the inspector.

 GameObject instanceBox = Instantiate(SpawnedBox.gameObject, transform.position, transform.rotation) as GameObject;
     SpawnedBoxList.Add(instanceBox);
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 MDurkin · Oct 01, 2013 at 02:09 PM 0
Share

Rookie error :p ... thank you, this fixed the problem.

avatar image AjayKhara · Oct 01, 2013 at 02:24 PM 0
Share

Please vote it. So that others may find it helpful

avatar image
0

Answer by Hoeloe · Oct 01, 2013 at 01:41 PM

NullReferenceException comes when you try to use an object that does not exist (that is, it is null). On the line you've quoted, there are two objects that could give your error, instanceBox, or SpawnedBoxList.

You're doing a lot of unnecessary casting anyway. Since instanceBox is a GameObject, calling .gameObject on it just returns the same object, and casting it to a GameObject again does nothing, so you could reduce:

 SpawnedBoxList.Add((GameObject)instanceBox.gameObject);

to just:

 SpawnedBoxList.Add(instanceBox);

I think it more likely that SpawnedBoxList is null, though, so be sure to set it correctly (i.e. SpawnedBoxList = new List()).

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 vexe · Oct 01, 2013 at 01:50 PM 0
Share

Gonna have to disagree a little bit, as Instantiate returns a UnityEngine.Object, and not a UnityEngine.GameObject (which inherits from UnityEngine.Object) So you do need a to cast what Instantiate spits either by an as cast (which returns a null if it fails) or a normal cast (which returns a InvalidCastException exception upon failure) :)

avatar image Hoeloe · Oct 01, 2013 at 02:08 PM 0
Share

Ah, oops. Sorry, I'm clearly a little out of it. I also missed that he was adding to a list, which could also throw a NullReferenceException if the list is null. You're absolutely right.

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

19 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

Related Questions

Multiple Cars not working 1 Answer

Need help with ArgumentOutOfRange Error 1 Answer

NullReferenceException yet Debug.Log shows nothing is null? 1 Answer

Cannot convert float to int when only using floats (C#) 3 Answers

Argument out of range exception 2 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