Javascript inheritance

So I have a function I need to call and it’s not working. The order of inheritance goes like this:


The error I get is: ‘MyFunction’ is not a member of ‘A’

private var curTransform		:Transform;				//Holds the transform of the object
private var curScript		:A;			//Holds the script of the object

function ThisFunction()
    curTransform = hit.transform;//Get the object transform
    curScript = curTransform.GetComponent(A);//Get the objects script

So, the script that is on the object is ‘D’, it doesn’t matter which script i ask for in the GetComponent call, they all return script ‘D’, the function I’m trying to call is on script ‘B’ and the variable holding script ‘D’ is declared as type ‘A’.

Moving the function i need to call to script ‘A’ works, but Only objects with scripts B and above are allowed to use MyFunction.

Changing the type of the variable to type ‘B’ works, but the variable needs to be able to hold scripts of type A and above so it must stay as type ‘A’.

So obviously those solutions won’t work for me or I wouldn’t be here asking for help :slight_smile:

Thanks in advance!

So that’s inheritance for you - you can’t call a function which is declared in class B if you have a variable that is typed as class A, where the function does not exist.

The compiler needs to be able to call that function no matter what A derivative is stored in the variable. I’m afraid that is exactly what you should expect will happen. A 4 level deep inheritance architecture is already asking for trouble I have to tell you.

The best thing to do would probably be to put the function MyFunction in an interface and then check if A implements that interface before calling it.

  interface IDoMyFunction
        function MyFunction();


   var curFuncProcessor : IDoMyFunction = curScript;
   if(curFuncProcessor != null) curFuncProcessor.MyFunction();

Well since your variable is of type A but A doesn’t have the function you need to cast it to at least B. Keep in mind that the cast can fail if the instance in your variable is not of type B or a derived version of B, so make sure you check for that. UnityScript doesn’t have the is-operator to test for a specific type, but you can simply use the as-cast which will return null if the reference can’t be casted:

function ThisFunction()
    curTransform = hit.transform;
    curScript = curTransform.GetComponent(A);
    var bScript = curScript as B;
    if (bScript != null)