[SOLVED] Call the variable from other script

Currently I doing on add specific layer to camera and object. I create a variable in a scriptA and i console.log the variable it work fine. After that I try to call the variable in scriptB and add the variable into Object layer. I try to console.log the variable from scriptA to scriptB, it give the result undefined.
This the script A where I define the variable

    this.layer= this.cameraEntity.camera.layers[0];
    console.log(this.layer); //give out the result room1 in the console

This is script B where I wanna call the variable layer. and add the layer into the objects layers.
PS: I already add the attribute in the top call net

    console.log(this.net.script.network.layer); //give out the result undefined in console

But if I console.log(this.net.script.network) (in scriptB) it give out an array which also say the layer:room1.

Can I ask what going wrong that I unable to get the room1 variable name or something that I missed?

Sincerely Elliot.

Hi @Elliot,

Your code seems correct, and if scriptB runs after scriptA I imagine it should work. Not sure what’s the issue, are you able to share a sample project take a look?

Here my project link.

So yes, the problem here is that you try to print the layer property before it’s being initialized.

If you observe in the network.js script it will receive a value after the socket has been opened and the playerData event is received. That can take a while.

On the other hand in the movement.js script your console.log() statement will run as soon as the entity is enabled, way before what happens in the other script.

One solution to your problem is to use PlayCanvas events to communicate when the layer property is ready:

// movement.js
Movement.prototype.initialize = function() {
    this.force = new pc.Vec3();
    this.app.on('onPlayerData', function(){
    }, this);
// network.js
Network.prototype.initializePlayers = function (data) {
    this.players = data.players;
    Network.id = data.id;
    this.layer= this.cameraEntity.camera.layers[0];
    for(var id in this.players){
        if(id != Network.id){
            this.players[id].entity = this.createPlayerEntity(this.players[id]);
    this.initialized = true;

1 Like

Thanksss @Leonidas It work fine now. :smiling_face_with_three_hearts: :smiling_face_with_three_hearts:

Thank for helping me to fix this again!!!

1 Like