You can also expose functions directly to the global scope with this code. I use it a fair amount for my Vue.JS app, it’s the same as going through pc.app.root.findByName('entity name').script.scriptName.yourFunction()
, just a little more convenient.
In your PlayCanvas script:
// Global function
window.yourFunction = function (x, y, z) {
var app = pc.Application.getApplication();
var entity = app.root.findByName("Name of Script Entity");
entity.script.scriptName.yourFunction(x, y, z);
};
// Script function
scriptName.prototype.yourFunction = function(x, y, z) {
return x + y + z;
};
EDIT - USE PLAYCANVAS EVENTS INSTEAD
Since posting this I’ve looked more into switching to PlayCanvas events. I’m now convinced that’s the best approach, both in terms of ease-of-use and best practices. I’ve since switched to using PlayCanvas events in my projects, I don’t want to leave this post here with bad information. Implementing events was easier than expected and your code looks cleaner too.
To use PlayCanvas events do this instead:
In your PlayCanvas script:
scriptName.prototype.initialize = function() {
this.app.on('creativeEventName', this.yourFunction, this);
};
// Script function
scriptName.prototype.yourFunction = function(x, y, z) {
return x + y + z;
};
From another PlayCanvas script:
this.app.fire('creativeEventName', x, y, z);
From any JS script:
pc.Application.getApplication().app.fire('creativeEventName', x, y, z);