Changing the texture of a material using a button

Hi! I want to change the color of a cube in my scene using a button press. I have written the following code but it does not do anything.

Here is the code:

var buttonPress = pc.createScript('buttonPress');

// initialize code called once per entity
buttonPress.attributes.add("materials", {type: "asset", assetType: "material", array: true, title: "Materials"});

buttonPress.prototype.initialize = function() {
    var self = this;
    this.materialIndex = 0;
    this.entity.Button.on('click', function(event) {
    }, this);

buttonPress.prototype.changeToNextMaterial = function() {
    // Get the next material asset in the array 
    this.materialIndex = (this.materialIndex + 1) % this.materials.length;
    var material = this.materials[this.materialIndex];        

    // Assign the material to all the mesh instances in the model
    var meshInstances = this.entity.model.meshInstances;
    for (var i = 0; i < meshInstances.length; ++i) { 
        var mesh = meshInstances[i];
        mesh.material = material.resource;

Can anyone help?

Hey Rushil, the B in button should not be capital.

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

Also, try debugging the “changeToNextMaterial” function to see if all the variables have their required value.

Thanks @saif !! I figured out the problem. Actually my scene used a render and I was trying to use the meshInstances of a model instead. It works fine now.

1 Like