[SOLVED] Calling Playcanvas function from anonymous function

Hey everyone,

I am trying to call a playcanvas function from an anonymous async functiojn in my code, but I cannot seem to get it to work. The code is as follows.

Rating.prototype.rate = function(letter) {

const predict = async function(arr) {
    let inputCalc = tf.tensor(arr);
    let data = inputCalc.reshape([1, 8]);
    const model = await tf.loadLayersModel('https://raw.githubusercontent.com/ABcoder29/special-tribble/main/model.json');
    let tensorOutput = model.predict(data);
    let finalRes = parseFloat(tensorOutput.dataSync()[0]);
    if (finalRes < 8) {
    else if (finalRes >= 8 && finalRes <= 10) {
    else if (finalRes > 10 && finalRes <= 12) {
    else if (finalRes > 12 && finalRes <= 14) {
    else {

predict is getting called correctly, as if I change the alert in the rate() function to a simple string, it works. However, I cannot access the this keyword inside rate. This doesn’t change even if I use pc.Application.getApplication(). The error I get is -

Uncaught (in promise) TypeError: Cannot read property 'name' of undefined
    at ScriptType.Rating.rate (rating.js?id=37158208&branchId=5bd3b56e-5a78-477a-a019-68fe536f0036:86)
    at predict (rating.js?id=37158208&branchId=5bd3b56e-5a78-477a-a019-68fe536f0036:110)

How do I fix this?

Hi @DevilZ,

You need to grab a reference to the entity first that holds that script, and then run the method:

// pseudo code
var app = pc.Application.getApplication();
var myEntity = app.root.findByName('myEntity');
1 Like

So use this code instead of Rating.prototype.rate inside predict’s if statement?

A JS prototype method can’t be used directly, but only by calling it on an object instance that uses this class. So yes, try with the code I’ve posted.

Alright, will give it a try tomorrow morning(it’s quite late here) and revert. Thanks a lot for your quick response.

1 Like

You can also pass the script instance as param into the predict function.


Confirming that this works, just had to change app.findByName to app.root.findByName. Other than that it was perfect. Thanks again @yaustar and @leonidas.

1 Like