Interfaces and Components - Javascript

Hello,

I am creating several different components. But I would like all of these components to share a common interface so that I can call specific functions on them without having to know their data type. How can I achieve this in Javascript? I could use SendMessage, but I cannot retrieve return values with this method. I have heard about Interfaces, but I am not sure how to work with these in Javascript for this purpose.

Thanks in advance.

interface SomeInterface {
    function DoSomething();
}
class SomeClass implements SomeInterface {
    function DoSomething() {

    }
}

Make sure your interface file name is not the same as the name of the interface contained within. Unity tries to turn it into a class and you’ll get reference errors.

Interesting to know. Thank you for the reply.

Perhaps I am missing something however, but I am not sure how that solves the problem. My aim was to be able to create a set of components, each with a different implementation, and be able to use the GetComponent function to retrieve a reference to any of those components by way of passing the Component base type as an argument (or some common type), and then to call a function on the returned component without knowing its sub-type, because all the components implemented a common interface. EG:

And then

It seems to me from your code though that a class implements an interface only by using the implements keyword in the class declaration. This is a problem, I think, because Javascript does not (as far as I know) allow me to edit the class declaration for a component. It creates one for me implicitly and does not show it in the source file. Presumably this means that I cannot make a component implement an interface. If I cannot make a component implement an interface, then presumably I cannot call a function on them unless I know their type after all?

Thanks.

Sure you can. Just because Unity does it for you doesn’t mean you can’t do it yourself.

This is perfectly ok.

class SomeClass extends MonoBehaviour implements SomeInterface {

}

I have heard some people talk about GetComponent on interfaces being unreliable and/or not working well in UnityScript. I’ve used it a bunch of times in C# to get a base class that a bunch of classes inherit from, but never done this specifically in UnityScript. Someone else might be able to speak more to that.