Creating custom methods for entities

Hey,

We just made a new tool to help with our development in PlayCanvas.
To make the interface with other parts of the project as smooth as possible we want to mirror the interface of the default components, such as described in the API of the sound component.

In order to do so we would need to create methods similar to for instance:

this.entity.sound.play();

ex:

this.entity.customtool.customfunction();

Is there an available way to do so? Or would we need to digg into the PC source code?

Hi @Astra,

You could potentially add your own custom component system, that will be available in code. Of course it won’t show up in editor and given this fact I’m not sure what’s the use then.

So if you just want the object signature to look like that, you can do so like this:

// add a custom object
this.entity.customtool = {};

// now add properties/methods to the object
this.entity.customtool.customfunction = function(){
   // my method
};

And you can call it:

this.entity.customtool.customfunction();
1 Like

ok… that makes a lot of sense, thx!!

As to why: Basically we fire a lot of events when different things happen in that tool. Just like the sound component fire ‘pause’ when it is paused. However, rather than firing a similar message back at the tool when we want to ‘pause’ the sound from a different script we wanted to use a method like for the sound component. Just to keep it a bit simpler and consistent with the other API :slight_smile:

1 Like

You could also extend the prototype of objects in a script file after the engine is loaded

eg

(function(){
pc.Entity.prototype.foobar = function() {
  // do something
};
})();

And have the script loading type to be ‘after engine’. Then foobar should be accessible to all Entities

1 Like

huh. That could be rly neat. Thx!