Standalone + TypeScript - Create a script and add it to Entity

The examples I’ve looked at use scripts written in JavaScript and stored in separate files. Maybe I didn’t see the right example, but how do I create a TypeScript script and how do I attach it to an entity in the Standalone version?

This example (PlayCanvas Examples) creates a script, but when I try to repeat it, it writes that the initialize method does not exist in ScriptType. The ScriptType class itself is deprecated.

I finally got it done:

const Locomotion = createScript('Locomotion');

// initialize code called once per entity
if (Locomotion) {
        Locomotion.prototype.initialize = function () {
                console.log('init');
        };

        Locomotion.prototype.destroy = function () {};

        // update code called every frame
        Locomotion.prototype.update = function (dt: number) {
                console.log(dt);
        };
}

this.box.addComponent('script');
if (this.box.script) {
        this.box.script.create('Locomotion', {});
}

Another way, more convenient:

class MyScript extends ScriptType {
    initialize() {
        console.log('init');
    }

    update(dt: number) {
        console.log(dt);
    }
}
registerScript(MyScript, 'myScript');

But what about the deprecated ScriptType class and the methods (initialize, destroy, update) that this class doesn’t have?

@Mark_Lundin

You can still use the ScriptType class for the foreseeable future, so you’re second example should be fine in the editor. We are imminently releasing an improved Scripting system, but this won’t impact existing ScriptType scripts, so you can continue using this

1 Like