[SOLVED] How to access a variable defined in another script?

How to call other script file variable?
For example, I have Player.js and Enemy.js file
In Player.js file, I want to call variable from Enemy.js
How to do it ,thank you very much

Player.js

var Player = pc.createScript('player');
Player.prototype.initialize = function() {
  this.dosomething = false;
}

Enemy.js

var Enemy = pc.createScript('enemy');
Enemy.prototype.initialize = function() {
  Player.dosomething = false;  //How to call other script file variable?
}

See thread [SOLVED] Accessing members of another Entity

However, it’s usually recommended to use PlayCanvas events instead: https://developer.playcanvas.com/en/user-manual/scripting/communication/

2 Likes

Thank you reply and sorry about that.
it still not work me…

Here is my Demo project
https://playcanvas.com/editor/scene/889321

Player.js

var Player = pc.createScript('player');

Player.prototype.initialize = function() {
    this.dosomething = false;
};

Enemy.js

var Enemy = pc.createScript('enemy');
Enemy.attributes.add('playerEntity', {
    type: 'entity',
    title: 'player'
});
Enemy.prototype.initialize = function() {
    console.log(Player); // Can see Player information
    console.log(this.playerEntity.script);  // underdefined
};
1 Like

Hi @supsersuperman,

Your code is your correct, you are missing only a single step, add the Player entity on the script attribute in editor.

To do that first press Parse and then drag and drop the Player entity in place:

3 Likes

@Leonidas
Woooooo
Thank you very much, It work fine!!! :smiley:

1 Like