I ended up temporarily changing the way I had my stuff coded since I’m on a deadline at school, but for future reference, I’m having issues with classes extended from other classes. This is easier to show than it is to explain:
I declare my class and subclass:
class Base {
function DoSomething() {
//does something
}
}
class Sub extends Base {
function DoSomething(with : parameter) {
//Does something using parameters
}
}
class Sub2 extends Base {
function DoSomething(with : parameter) {
//Does something slightly different with parameters
}
}
Later, while trying to use this code, I need to reference either one of these two classes in the same variable (for example, both are CharacterClass, but one is NPC and the other is PC, and one variable is used for both versions of Base). It won’t let me use the derived version of DoSomething, and returns that I can’t call it with parameters (as none are set in Base’s constructor, even though it is in each of its children.
var subGuy : Sub = new Sub();
var sub2Guy : Sub2 = new Sub2();
var myBase : Base;
if (something) {
myBase = subGuy;
} else {
myBase = sub2Guy;
}
myBase.DoSomething(myParam);
The above throws an error, and since the same command is used in both instances, I can’t simply use ( myBase as Sub ).DoSomething(myParam); As I never don’t intrinsically know which of the two versions I have (and it returns a Base, not a Sub or Sub2 version of the myBase).
Is there any way to access the inheritor’s function to perform the task?
“DoSomething()” and “DoSomething(with : parameter)” are not the same method, as the paramter list is part of the signature. So one can not override the other.
Also “DoSomething(with : parameter)” is not defined in your base class, only the other one.
The point of inheritance is that you have to use virtual functions so they can be overridden in a sub class. AFAIK it works like this in UnityScript:
class Base {
virtual function DoSomething(parameter : int) {
Debug.Log("Base " + parameter);
}
}
class Sub extends Base {
virtual function DoSomething(parameter : int) {
Debug.Log("Sub " + (parameter * parameter));
// to call the overridden function from base:
super.DoSomething(parameter);
}
}
As far as i know there’s no “override” keyword in UnityScript. It automatically overrides the function as long as it’s virtual.
var c : Base;
c = new Sub();
c.DoSomething(5);
This would print:
"Sub 25"
"Base 5" // because i call the base (super) version
Like others have already mentioned the signature of a function is defined by it’s name and it’s parameters. Otherwise it’s not the same function. If you have multiple functions with the same name but different parameters it’s called an overloaded function since it exists multiple times. The compiler picks the correct version according to the parameters you pass in.