[SOLVED] Swapping 2D Texture at Runtime

Hey all,

I posted awhile ago about making a toggle switch but have decided to implement it from scratch. Right now I’m trying to swap the background image which acts as the button but whenever I swap the texture I get a white rectangle and no errors in the console. Is this just a simple code error? This feel like a silly thing to be making a post about because I know it is extremely simple but I have yet to find the solution.
Here is the code:

var ToggleUi = pc.createScript('toggleUi');
ToggleUi.attributes.add('offTex', { type: 'asset', assetType: 'texture' });
ToggleUi.attributes.add('onTex', { type: 'asset', assetType: 'texture' });

// initialize code called once per entity
ToggleUi.prototype.initialize = function() {
    this.isOff = true;
    this.entity.button.on('touchend', this.toggle);
};

ToggleUi.prototype.toggle = function() {
    if(this.isOff){
        console.log("toggle on");
        this.isOff = false;
        this.entity.element.texture = this.onTex;
    }
    else{
        console.log("toggle off");
        this.isOff = true;
        this.entity.element.texture = this.offTex;
    }
};

And here is what it looks like before clicking it:
Screen Shot 2022-03-08 at 12.20.26 PM
And then here it is after doing the swap:
Screen Shot 2022-03-08 at 12.20.33 PM

Thanks in advance.

Hi @Jake_Johnson,

If this.onText and this.offText are assets, then you need to assign their resource to the element, instead of the assets directly.

Like this:

this.entity.element.texture = this.onTex.resource;

I had tried that previously since that is how it works with other assets but whenever I do that here I get this error:
Uncaught TypeError: Cannot read properties of undefined (reading 'resource')
I’ve double checked to make sure it is hooked up in the editor to the correct png’s and it is

Not sure then, try using the debugger to verify those assets are correctly defined. Since the compiler throwing that error means they aren’t.

If you keep having a problem try sharing your project to take a look.

I’m not finding anything out of the ordinary. Let me gut the project and send it (its for a client so I can’t share some things)

@Leonidas
There you go: PlayCanvas 3D HTML5 Game Engine

Hi @Jake_Johnson,

Nothing is wrong with changing the texture code, the issue is that you are not passing the “this” context to the function, this should fix the issue:

this.entity.button.on('touchend', this.toggle, this);
this.entity.button.on('mouseup', this.toggle, this);
1 Like

@Saad_Haider yep that was it. Thanks man. Silly of me to forget and then subsequently not notice :stuck_out_tongue_closed_eyes: