- Home /
How to reassign a variable's class
Hi, I've got an instance where I need to change the class of a variable so that it could be one of two classes. How would I do this?
var aVar;
var aNum:int;
if(aNumb == 1)
{
// aVar gets class 'fish'
}
else if(aNumb == 2)
{
// aVar gets class 'bird'
}
Answer by DaveA · Feb 21, 2012 at 11:45 PM
Make a common superclass, like 'animal' and derive 'fish' and 'bird' from 'animal' Then if the var is of type 'animal' it should accept 'fish' or 'bird'
untested:
class Animal ( can add 'extends MonoBehaviour' here if it would be such a thing)
{
var legs : int; // for example
}
class Bird implements Animal
{
Bird() { legs = 2; } // constructor to initialize whatever
}
class Fish implements Animal
{
Fish() { legs = 0; }
}
var f : Fish = new Fish();
var b : Bird = new Bird();
var a : Animal;
a = f;
a = b;
When I put 'implements' it gives an error and asks if I meant 'extends' does that make sense? I'm using Java Script if it helps.
It doesn't work for me. Did you change something in the code that DaveA provided (apart changing "implements" to "extends")?
Your answer
Follow this Question
Related Questions
Accessing variables from seperate scripts 1 Answer
Missing Documentation on accessing Variables 1 Answer
Can I choose what to pass into .getcomponent<{VARIABLE}>(); 1 Answer
Class functions don't seem to be updating class variables 1 Answer
How do you assign the class of one varriable to another? 2 Answers