- Home /
Static array with custom class?
So I thought I had figured out static variables until I ran into this problem:
Works:
//ScriptOne
static var lot = new int[4];
static function output () {
var ret = lot[0];
return ret;
}
Doesn't work:
//ScriptOne
class pig{
var weight:int=6;
}
static var lot = new pig[4];
static function output () {
var ret = lot[0].weight;
return ret;
}
//ScriptTwo
function Update () {
Debug.Log(ScriptOne.output());
}
NullReferenceEception on play
It appears that an array whose type is a custom class cannot be made static. Is there a workaround or a better way to do this that works? I am writing a script that I want to be treated as a library of functions and in this case there should only be one instance of the array at a time so it made sense to make it static. Am I missing something?
Answer by gfr · Nov 02, 2011 at 09:57 AM
You have initialized the array, but not it's contents. For basic types (like int
s) that fine, but not for class-types. You need to initialize the array contents once.
Yeah I initialized it. var lot = new lot[] is the same as var lot:lot[] = new lot[4];
I also tried changing a variable using an initialize function that I called in the start of scriptTwo and the results were the same. If you are sure that's whats going on could you post an example?
@TheAssassin: I meant actually initializing the contents of the array. For class-types those are references and have to be set to specific instances, otherwise they refence nothing. $$anonymous$$g.:
for (var i=0; i<lot.length; ++i)
lot[i] = new pig();
This is the same with non-static arrays.
Sorry I was in a hurry and didn't fully look into what you were saying. It works Great thanks!
No problem, i guess putting in a code-snippet right away would have been better to avoid misunderstandings.