- Home /
varible type class not working if not declared public
This code doesn't work unless var testing : Test is declared outside of Start(). It returns a NullReferenceException: Object reference not set to an instance of an object. Sorry about the bad title.
Thanks for any insight.
class Test { var a : boolean; var b : int; }
function Start() { var testing : Test; testing.a = false; }
Answer by Flynn · Jun 27, 2011 at 03:49 AM
var testing : Test = new Test();
This goes into memory handling in code -- There are two types of variables, basic variables, and objects.
Basic variables are ALL either a number type (float, integer, double, long, short, word, long long, etc) or a boolean value. They are stored in a special part of memory.
Then, you have objects. All object variables are actually (internally) numbers referring to a point in memory that contains the actual object. The quirk of this is that objects must be created with "new Type()", allocating a spot in memory, and telling the variable where to point to. Because basic values are smaller, and less dynamic than objects, they don't need a reference to their location. Instead of a reference, they just have the value they store, so, they get defined automatically.
In short, any custom class must be created with new ClassName()
thanks. But why doesn't it always need to be declared like that?
This is a Unity "feature". All public variables are initialized by Unity when they belong to a $$anonymous$$onoBehaviour so they can be edited in the inspector.
Unity does definitely define object type variables for you if they are public. Auto definition of simple/basic variable types though is something existent throughout all program$$anonymous$$g
Answer by Eric5h5 · Jun 27, 2011 at 04:08 AM
If you make it a struct, then it has default values of 0 like Vector2, Vector3, etc., and you don't need to use new ClassName(). Small simple classes that only use base types like int, float, etc. are good candidates for structs.
class Test extends System.ValueType
{
var a : boolean;
var b : int;
}