Attach script via attribute

I want to add a script that is attached via attribute. My code works but is there a nicer way to check if it the entity has this script or to create it (do I need the name for that? I have the script already as asset in the variable this.runScript. When I use:
Bildschirmfoto 2020-09-18 um 17.54.22
it doesn’t work anymore.

var DoAdditionalThings = pc.createScript('doAdditionalThings');
DoAdditionalThings.attributes.add('runScript', {
    type: 'asset',
    title: 'Script to run',
    description: 'Script that will be executed'
});
// initialize code called once per entity
DoAdditionalThings.prototype.initialize = function() {
    if(this.runScript.file){
        var filenameWithSuffix = this.runScript.file.filename;
        this.filename = filenameWithSuffix.split('.').slice(0, -1).join('.');
        if(!this.entity.script.has(this.filename)){
            this.entity.script.create(this.filename);
        }   
    }
};

What is in the script that is running?

It sounds like a global function would be easier to do here?

What I do is to trigger model animations and sometimes additional actions (like switch light on an off, change material, etc) from several triggers by using always the same script. Therefore I check if there is this script in place and simply add my individual script that should be executed. So I don’t need to care about any additional trigger events.

I would probably do it via a separate playcanvas script that is also attached to the entity but have the function/logic triggered by an event.

var SomeScript = pc.createScript('SomeScript');

SomeScript.prototype.postInitialize = function() {
    this.entity.fire('trigger_action');
};

var SomeAction = pc.createScript('SomeAction');

SomeAction.prototype.initialize = function() {
    this.entity.on('trigger_action', function() {
        console.log('do stuff');
    }, this);
};

This way you can have multiple/different actions on an entity that will run some logic when the event is fired.

1 Like

Yes, you’re right. It’s still hard for me to understand and use my own eventlistener. Thanks a lot. This helpes a lot!

I tried it out. Works fine and saved me a whole script!

1 Like