[SOLVED] Button to Change Color

Hello, I’ve recently found this platform and it looks fantastic.
I’m trying to make a simple button onClick action to change color of an object. I’m currently working on Modelviewer Template, I’ve added three buttons to the scene and also created a script but I’m not sure what’s the problem is. I’m using Google Gemini to assist me, I’d be glad if someone lend me a hand.

Link to the Editor: PlayCanvas | HTML5 Game Engine

// changeColor.js

var ChangeColor = pc.createScript('changeColor');

// initialize code called once per entity
// Button script
function onClick(event) {
  // Get reference to the model entity
  const modelEntity = this.entity.parent.findByTag("play");

  // Get the material component
  const material = modelEntity.getComponent("Material");
  // Set the new color based on the button (modify as needed)
    if (this.entity.name === "Button1") {
    material.set("Diffuse", new Color(1, 0, 0)); // Red
  } else if (this.entity.name === "Button2") {
    material.set("Diffuse", new Color(0, 1, 0)); // Green
  } else if (this.entity.name === "Button3") {
    material.set("Diffuse", new Color(0, 0, 1)); // Blue

There are various ways you can structure a project to achieve this. Here’s one solution:


The script I wrote to achieve this is as follows:

var SetColor = pc.createScript('setColor');

// Attribute to reference the target entity
SetColor.attributes.add('targetEntity', {
    type: 'entity',
    title: 'Target Entity'
SetColor.attributes.add('color', {
    type: 'rgb'

// initialize code called once per entity
SetColor.prototype.initialize = function() {
    this.entity.button.on('click', function() {
        // Collect all render components from the target entity and its children
        const renderComponents = this.targetEntity.findComponents('render');

        // Change the color of each render component
        renderComponents.forEach((render) => {
            if (render && render.material) {
    }, this);
1 Like

Hello thank you for reply, I’m trying to get it done with an object such as .glb files. I’ve seen some other projects that works on XR using the same object in my project. For example this project: PlayCanvas | HTML5 Game Engine
but I didn’t understand how that worked.

My script would work with GLB-based assets too. What don’t you understand?

for some reason I don’t get the targetEntity and color options in Editor. Also I’m getting “debug.js:107 script ‘changeColor’ is not found, awaiting it to be added to registry” even thou I’ve added my script on button components just like your example.

You have to parse the script in the Editor to see the attributes:

1 Like

thank you so much informations you gave me helped me very much my issue has been solved.

1 Like