Change button image on click

I’m making a play/pause button, so I need the image on the button to toggle on click. I’m using the hover/pressed state to tint the button (regardless of active image).

I’ve attached a script to the button, and I can see from the api ref that ButtonComponent has an imageEntity property. Question is, what’s the recommended way of changing the image of the button? I’m using pngs for the button images, so do they need to be made into templates I then instantiate?

Hey @MattN,
When it’s just two states, like “Play”/“Pause”, it’s easier to have the two entities with the separate images in the correct position(s), with one enabled at a time. When you want to swap them, you can do this -

this.app.root.findByName("Button1").enabled = false;
this.app.root.findByName("Button2").enabled = true;
//rename buttons as per your application.

Something that you can do to improve the organization of your project is have an entity that both the buttons are children of(“PlayPause” in my example below), and then do the same thing -

this.entity.findByName("Play").enabled = false;
this.entity.findByName("Pause").enabled = true;
//here we are pausing the game.

this.entity.findByName("Pause").enabled = false;
this.entity.findByName("Play").enabled = true;
//here we are playing the game.

This script is then attached to the “PlayPause” entity.

Hope this helps!

Ah of course, that’s a much simpler approach. I was trying to be too clever with it!

Thanks for your help

1 Like