|
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.
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 Maybe I'm just not understanding how lists work in C#. Anyone have a good answer for this one?
(comments are locked)
|
|
You need to create the list before using it.
The reason you're getting null reference exception is because SeedBox always was null for you. On a completely different note; you probably shouldn't call GameObject.Find every update. You can store the references during start instead: 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 Thanks though. And yeah, I forgot about GameObject.Find on Update... this is month-old code I wrote and just came back to today. :)
Jan 07 '11 at 09:09 PM
Jason B
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).
Jan 07 '11 at 09:13 PM
Statement ♦♦
...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
Jan 07 '11 at 09:13 PM
Jason B
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.
Jan 07 '11 at 09:15 PM
Statement ♦♦
No it wasn't. You had System.Collections but the list is in System.Collections.Generic.
Jan 07 '11 at 09:15 PM
Statement ♦♦
(comments are locked)
|
