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.
// 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
}
}
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) {
render.material.diffuse.copy(this.color);
render.material.update();
}
});
}, this);
};
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.
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.