- Home /
Referencing subclass in Unity JS
Unity JS lets you declare a subclass, or a class inside of a class, but how do you reference the subclass?
class Bunny{ var name:String="FooFoo"; var ears:int=2; var color:Color=new Color(1,0,0,1); class Abilities{ var speed:int = 1; var smarts:float = 0.3f; } };
var bunny = new Bunny(); var bunnyAbilities = new Abilities(); // doesn't work
Answer by fafase · Nov 07, 2012 at 07:10 PM
It is possible to access your inner class though it does not make much sense to me. You would be using a set of variables and methods that would require one more level of dereferenciation. On the other hand, you cannot instantiate an object of the type of the inner class.
class Outside{
var integer:int;
class Inside{
var intInside:int;
function Inside(){ //Constructor of the inner class
intInside = 10;
}
}
function Outside(){ // Constructor of the Outside class
integer = 0;
}
var inner:Inside = new Inside(); //Create an object of type Inside
}
var obj:Outside = new Outside();
// var objIn:Inside = new Inside(); //Error, type not found
function Start () {
print(obj.inner.intInside);//Access but one more dereferenciation.
obj.inner.intInside = 15;
print(obj.inner.intInside);
}
you can access the members of Inside but you need to dereference from the created instance inside the class.
You may have a proper reason for that and there may be some use for this feature. I just do not see it.
Answer by Montraydavis · Nov 07, 2012 at 04:54 PM
Separate your classes, and make a reference like so.
class BunnyAbilities{
var speed : float = 1 ;
}
class Bunny{
var Abilities : BunnyAbilities ;
}
var bunny = Bunny ;
function Start ( )
{
bunny.Abilities.speed = 4; //Change speed at start .
}
I personally LOVE LOVE LOVE class, and use it probably more than any other structured code .
Using this way compare to my way, you can declare instances of both classes.