Get component by some "interface"

I wanted to ask if there is a mechanism with getting components via an interface (similar to Unity’s getcomponent method when used with Interfaces)

A small C# code sample will probably explain:

interface Movable { bool canMove(); }
class SometimesMove : Movable { bool canMove() { return false; } }
class AlwaysMove : Movable { bool canMove() { return true; }}

if (currentEntity.GetComponent().canMove()) {

Whereas my code in playcanvas looks more like this:

if (currentEntity.script.SometimesMove) result = currentEntity.script.SometimesMove.canMove();
if (currentEntity.script.AlwaysMove ) result = currentEntity.script.AlwaysMove .canMove();

if(result == true) {

You could define methods and properties on entity instead of script. So it would be:

if (currentEntity.movable) {
    // movable
}

It’s javascript, and allows you to do pretty much anything without restrictions, just ensure not to get into troubles because of that :smiley:

Hi Max,

Thanks for your answer.

I am not sure how that solution would work with Script components?

I would like to keep the “movable” rules within components, and then attach the Component with the desired behaviour to the entity (in the editor)

In the case above, I would have a SometimesMove component and a AlwaysMove component, and then attach whichever one I wanted to a game entity (in the editor) - then any piece of code that wanted to check if the entity was movable would “just work”.

You can add any methods or properties to entity dynamically.

SometimesMove.prototype.initialize = function() {
    this.entity.canMove = false;
};
AlwaysMove.prototype.initialize = function() {
    this.entity.canMove = true;
};
if (currentEntity.canMove === true) {
    // canMove
}

Ah, that makes sense!

Thanks.