Variable not set properly on button click

what i am doing wrong?

I have variable “spinning” that i need to set to true on button click
in update i check if spinning is false and then nothing is done, if true it spins and after some spins it sets spinning to false plays tween and then it should set spinning again to true but it doesn’t register (it sets spinning to false but in update it’s false), here is the code:

var Controller = pc.createScript('Controller');
Controller.attributes.add('speed',{
    type:'number',
    default:80
});



// initialize code called once per entity
Controller.prototype.initialize = function()
{
    this.count = 0;
    this.spinning = true;
    this.s = true;

    this.spin.button.on('click',function(event)
    {

        this.count = 0;
        this.spinning = true;
        console.log("spin " + this.spinning);
    
    });
};


// update code called every frame
Controller.prototype.update = function(dt)
{
    console.log("update: "+ this.spinning + ":" + this.count +"|" + this.s);
    if(this.spinning == false) return;

        this.entity.translate(0,-this.speed*dt,0);
        var pos = this.entity.getLocalPosition();
		
        if(pos.y < -420)
        {
            this.count++;
            this.entity.setLocalPosition(new pc.Vec3(pos.x,450,pos.z));

            if(this.count == 5)
            {
                this.s = false;
                this.spinning =false;
                this.count = 0;
                this.tween = this.entity.tween(this.entity.getLocalPosition())
                            .to(new pc.Vec3(16,16,0),0.2,pc.BackInOut)
                            .loop(false)
                            .yoyo(false);
                 
                 this.tween.start();
            }
        }

    
};```
1 Like

Hi @mirkoni ,

It looks like you’re running into a problem with scope. Since you’re passing a new function in your click event, this is no longer working with the context of your script instance. You will want to change:

to:

    this.spin.button.on('click',function(event)
    {

        this.count = 0;
        this.spinning = true;
        console.log("spin " + this.spinning);
    
    }.bind(this));
4 Likes