Variables "this" declared in initialize doesn't get passed to a function within the same script

Hi all,

I am unsure why this is happening, but the “this.” variables I declared in initialize cannot be accessed by my function in the same script(point-and-click.js).

Project file: https://playcanvas.com/editor/scene/1373263

Here is my initialize:

image

however, it doesn’t carry through to a function written in the same script. Here is a screenshot from chrome’s debug tools:

2022-03-30_11h35_06

I checked another project that does the same thing and saw this:

2022-03-30_11h34_05

This unfortunately leads to a “reading” error since the variables don’t get passed. As a workaround, I redeclare the variables in the function (see screenshot below) just to get it to work, which I think only allows the other model to look at the player-controlled model (w,a,s,d) as opposed to walking towards it.

image

I read through the forums*(Variables declared in initialize function return errors later saying they are not defined)* and found how .this variables should be carried over to update, which I assume should also be carried to any functions within the script.

Is there a reason why this is happening? I am not sure if this is a bug or a feature that I need to consider when working on projects.

Any help will be greatly appreciated. Thanks!

Hi @spike_bump,

Your project seems to be private, I can’t open it to take a look at your code.

How are you calling your movePlayerTo method? The error you are reporting is quite common, in JS you need to specify the context when calling functions from a different context.

A common example is when using events, you can specify the context to be this as the third parameter of the event:

this.app.on('player:move', this.onPlayerMove, this);
1 Like

hi @Leonidas,

Sorry about that. I made it public again. I added two other models to see if it will follow the player using the same scripts. They do. I also tried using the scripts on my spiderman model but he still only looks at the player.

Hmm, your project seems to be inaccessible still:

image

hi Leonidas, sorry. Turned it public now. Someone made it private after I switched it awhile ago. It should be accessible now