- Home /
 
How do you assign the class of one varriable to another?
So I've got an instance where I need to create a local variable and assign it to be one of two variables, the problem is that both of those variables are different custom classes. So how do I make that variable equal to either?
Answer by DaveA · Feb 13, 2012 at 11:09 PM
The best way is probably to have a base class that you declare for all those, and then subclass from that your two different classes.
Ex:
 class A
 {
 }
 
 class B : A
 {
 }
 
 class C : A
 {
 }
 
 A myVar1;
 A myVar2;
 
 A myVar3 = new B();  or new C();
 
 myVar 1 = myVar3; // should work either way
 
               but you may need to explicitly cast things at some point too.
Didn't work. When I tried it Unity got mad at me and said it wasn't expecting ':' after 'class B'
You using JS? Then use 'implements' ins$$anonymous$$d of ':'
It didn't like 'implements' but it liked 'extends', do you think that should work?
Answer by aviose · Apr 18, 2012 at 11:08 PM
extends is the proper way to create a subclass in Unityscript. Dave's example would thus be the following in Unityscript:
 classA
 {
 }
 class B extends A
 {
 }
 class C extends A
 {
 }
 var myVar1 : A = new A();
 var myVar2 : B = new B();
 var myVar3 : C = new C();
 myVar1 = myVar3;
 
               The only thing I would worry about with this is the fact that even if you do set most of the same variables, it MIGHT drop the data that is exclusive to class C if you put it into a variable marked as a class A variable. (at the very least it will cause functions to default to the class A version, so you will have to set up a virtual version of it to force it to use the function from the subclass) That said, all 3 of these are considered class A regardless of the fact that one is class B and another is class C....
Your answer