- Home /
NullReferenceException and classes
Okay, I thought I understood all this, but now suddenly I'm at a loss. This NullReferenceException error (Object Reference not set to an instance of an object) gives me little information about what I'm doing wrong.
Basically, I have a class called "trigger", set up as just a bunch of variables like so:
class trigger {
var name:String = "Idle";
}
Then in another script, I attempt to make an array of these triggers, like so:
public var myCode:trigger[];
public function makeTrigger(howMany:Number){
myCode = new trigger[howMany];
Debug.Log("thisTrigger: "+myCode[0].name);
}
It's that Debug.Log line that pops the error. Obviously, anything more I try to do with my trigger class doesn't work. If I debug the length of myCode, I get the right number, but somehow the class is empty. I don't understand.
Any help would be just awesome. Thanks in advance, Jeremy
Answer by yoyo · Feb 11, 2011 at 05:31 PM
You've created an array of trigger references, but you still haven't created the triggers themselves. You need something like ...
public var myCode:trigger[];
public function makeTrigger(howMany:Number){
myCode = new trigger[howMany];
for (var i = 0; i < howMany; ++i){
trigger[i] = new trigger();
}
Debug.Log("thisTrigger: "+myCode[0].name);
}
(Apologies if my C# is showing, but you get the idea ...)
Ahhhh... thank you. I thought the myCode=new trigger[how$$anonymous$$any] did that automatically. Well, thank you so much. You just saved me hours of frustration.