I have an issue with inheritance. If I create a subclass object and call an overloaded variable/method the master class’ variable/method is used instead of the one of subclass. This behaviour is called static binding. By default dynamic binding is enabled in most script languages as long as static binding is not explicit definied.
Monoscript/Unitscript uses static binding, I don’t know why but I’m searching for a workaround…
class Animal
{
static var desc : String = "I'm an animal";
}
class Bird extends Animal
{
static var desc : String = "I'm a bird";
}
Anywhere in the code, I want “I’m a bird” as result!
var bird : Animal = new Bird();
Debug.Log(bird.desc);
→ Runs and prints: “I’m an animal”
// Another try
var bird : Bird = new Bird();
Debug.Log(bird.desc);
All classes in Unity are precompiled, so I came across a note that you normally shouldn’t define any constructors in MonoBehaviours. That lead me to the idea defining a constructor defining the inherited variables on instantiation.
JS (not tested):
public class Animal
{
public var desc : String = "I'm an animal";
}
public class Bird extends Animal
{
public Bird()
{
desc = "I'm a bird";
}
}
C# (tested):
public class Animal
{
public string desc = "I'm an animal";
}
public class Bird : Animal
{
public Bird()
{
desc = "I'm a bird";
}
}
And it works… looks like the effort to rewrite the classes was close to obsolete