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
2
Question by Jason B · Jan 07, 2011 at 08:47 PM · errornullreferenceexception

Null reference exception when using lists of my object.

This is a huge head scratcher (at least, it has been for me). I literally have only one problematic line of code I've written, that checks out in Visual Studio, but starting my game immediately boots me out with a null reference exception error based on that single line no matter how I jiggle it around or configure it or rephrase it. I have a lot of experience with collections of objects in VB, and as far as I can tell, I'm not doing anything wrong, but I've never used collections of objects in C#, so.

Here is my code.

using UnityEngine; using System.Collections;

public class CountInventory : MonoBehaviour {

 // Use this for initialization
 public static int CurrentWater = 50;
 public static int CurrentCash = 100;
 public static int ToolMode = 1;
 public static System.Collections.Generic.List<Seed> SeedBox;
 private Seed NewSeed;
 void Start ()
 {
     SeedBox.Add(NewSeed);
 }

 // Update is called once per frame
 void Update ()
 {
     GameObject.Find("GUIWater").guiText.text = "Water: "+CurrentWater;
     GameObject.Find("GUIMoney").guiText.text = "$"+CurrentCash;
 }

}

Now, another thing to note, before someone brings it up: I do have a Seed class, so I'm not trying to declare a type that doesn't exist. :) You may also ignore my Update, and Water/Cash/Toolmode variables. I just included everything for posterity.

Any time I try to do ANTHING with my SeedBox (which is declared as a list of Seeds, or it logically seems that way to me), it gives me null reference exceptions up the wazoo. I've tried all sorts of alternate codes in place of SeedBox.Add(NewSeed);. I've tried SeedBox.Add(new Seed());, I've tried directly talking to the index (by using SeedBox[0].SeedName or whichever other Seed variable)... nothing works.

Maybe I'm just not understanding how lists work in C#. Anyone have a good answer for this one?

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

1 Reply

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

Answer by Statement · Jan 07, 2011 at 08:55 PM

You need to create the list before using it.

using System.Collections.Generic;
...
public static List<Seed> SeedBox = new List<Seed>();

The reason you're getting null reference exception is because SeedBox always was null for you.
This has nothing to do with lists, collections or arrays. This is C# basics. All reference type objects are null by default. Unity create instances for you when you have public (not static) variables on scripts, so if you haven't coded C# outside of unity I can imagine you are having problems wrapping your head around it. :) But this is nothing more than you hadn't created the list in the first place.


On a completely different note; you probably shouldn't call GameObject.Find every update. You can store the references during start instead:

using UnityEngine; using System.Collections; using System.Collections.Generic;

public class CountInventory : MonoBehaviour { public static int CurrentWater = 50; public static int CurrentCash = 100; public static int ToolMode = 1; public static List<Seed> SeedBox = new List<Seed>();

 private Seed NewSeed;
 private GUIText water;
 private GUIText money;

 void Start ()
 {
     water = GameObject.Find("GUIWater").guiText;
     money = GameObject.Find("GUIMoney").guiText;
     SeedBox.Add(NewSeed);
 }

 void Update ()
 {
     water.text = "Water: " + CurrentWater;
     money.text = "$" + CurrentCash;
 }

}

Comment
Add comment · Show 6 · 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 Jason B · Jan 07, 2011 at 09:09 PM 0
Share

D'oh!

In defense of my stupid mistake, it sometimes confuses me because it seems like it's out of left field whether you need to use "= new " or not. For instance, I don't have to use private Seed NewSeed = new Seed, it just works the way it is. I've been doing C# in Unity for a couple months now and while I have most of it figured out, the only thing I don't understand is how I know beforehand whether I need to declare something as a "new " or not.

Thanks though. And yeah, I forgot about GameObject.Find on Update... this is month-old code I wrote and just came back to today. :)

avatar image Statement · Jan 07, 2011 at 09:13 PM 0
Share

Well, NewSeed is bound to be default(NewSeed), which is null if it is a class or default values if it is a struct. That's basically the rule there is to it. If it is a struct (value type) you dont need to new it, if it is a class (reference type) you need to new it (unless you handle nulls in an expected manner).

avatar image Jason B · Jan 07, 2011 at 09:13 PM 0
Share

...I also laughed out loud at myself when I realized System.Collections is already included and I typed it out in the longest, most redundant way possible. Good times. :P

avatar image Statement · Jan 07, 2011 at 09:15 PM 1
Share

Default values for structs are 0, false and null for all kinds of members. You can't have explicit default constructors with structs. If you do try to create default constructors on structs you get the following message: "Structs cannot contain explicit parameterless constructors". Likewise you can't set struct field initializers.

avatar image Statement · Jan 07, 2011 at 09:15 PM 0
Share

No it wasn't. You had System.Collections but the list is in System.Collections.Generic.

Show more comments

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

No one has followed this question yet.

Related Questions

how to set Object reference to an instance of an object 1 Answer

NullReferenceException: Object reference not set to an instance of an object DestroyByContact.OnCollisionEnter2D (UnityEngine.Collision2D coll) 1 Answer

Vector3.Distance giving me NullReferenceException every time 1 Answer

NullReferenceException problem 2 Answers

Error in changing color from sendmessage 1 Answer


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