Variables declared in initialize function return errors later saying they are not defined

Every time I try declaring a variable in the default initialize function and try accessing it in another function later it says the variable is not defined.
For example:

// initialize code called once per entity
CheckRoll.prototype.initialize = function() 
{
    var results = [1,2,3,4,5,6];
    var bestCount = 0;
    var bestValue = null;
    var secondCount = 0;
    var secondValue = null;
    var currentCount = 0;
    var currentValue = null;
    var diceValue = 0;
    
    var dice = this.app.root.findByTag('Dice');
    
    this.stopped = false;
    this.timer = 0;
};

This code returns an error saying diceValue is not defined when I try to access it later.
Full Code: https://playcanvas.com/editor/code/529780?tabs=10861152

This is because in JavaScript, local variables are released after the function called. If you want to access a variable in somewhere, you should make it as a instance property. Like:

CheckRoll.prototype.initialize = function() {
    var dice = this.app.root.findByTag('Dice');
    
    this.stopped = false;
    this.timer = 0;
    this.diceValue = 0;
};

So you can access this.diceValue in other methods of CheckRoll.

1 Like

Yup, that did it. Seems like everything is all about this..

1 Like

I was having the same problem, and using this. helped, but the variables seem to reset after every frame. Does anyone know how to help?
Here’s the code:


// initialize code called once per entity
PlayerControl.prototype.initialize = function() {
    this.xPos = 0
    this.yPos = 0
    this.zPos = 0

    this.xVel = 0
    this.yVel = 0
    this.zVel = 0

    this.xAng = 0
    this.yAng = 0
    this.zAng = 0

    this.xAngVel = 0
    this.yAngVel = 0
    this.zAngVel = 0
};

// update code called every frame
PlayerControl.prototype.update = function(dt) {

    //check input and change velocities
    if (this.app.keyboard.isPressed (pc.KEY_SPACE)) {
        this.zVel += 0.1
    }

    //move by velocities
    this.entity.setPosition (this.xVel, this.yVel, this.zVel)

};

Hi @Contranym and welcome!

I guess you are using an entity with a dynamic rigidbody. Unfortunately you can’t use setPosition() on an entity with a dynamic rigidbody. You need to add a force to the rigidbody instead.

Thank you! This really helped me.

1 Like

Yeah for some reason declaring local variables is quite weird, I always use this.x. For the most part I just pretend local variables do not exist, as I never use them except in code made by someone else.