[SOLVED] Need help changing Materials

Hello everyone, I’m very new to Playcanvas and Javascript and I need some help :sweat_smile: I’m trying to change materials (one at a time) whenever the RMB is clicked/down. I’ve been combing through the tutorials and videos on YouTube but my brain is still going blank. I’d appreciate the help! Thank you!

var SwitchMaterials = pc.createScript('switchMaterials');

SwitchMaterials.attributes.add("materials", {type: "asset", assetType: "material", array: true, title: "Materials"});

// initialize code called once per entity
SwitchMaterials.prototype.initialize = function() {
 var self = this;

    this.materialIndex = 0;
    
    // Change materials every second
    /*var handle = setInterval(function () {
        this.entity.changeToNextMaterial();
    }, 1000);
    
    this.on('destroy', function() {
        clearInterval(handle);
    }, this);*/

    // Change materials every mouse click
    this.app.mouse.disableContextMenu();
    this.app.mouse.on(pc.EVENT_MOUSEDOWN, this.onMouseDown, this);

};

// update code called every frame
SwitchMaterials.prototype.changeToNextMaterial = function(dt) {
    var i = 0;
    
    // 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 allMeshInstances = [];
    var renders = self.findComponents('render');

    for (i = 0; i < renders.length; ++i) {
        var meshInstances = renders[i].meshInstances;
        for (var j = 0; j < meshInstances.length; j++) {
            allMeshInstances.push(meshInstances[j]);
        }
    }      

    for (i = 0; i < allMeshInstances.length; ++i) { 
        var mesh = allMeshInstances[i];
        mesh.material = material.resource;
    }
};

SwitchMaterials.prototype.onMouseDown = function (event) {
//Whenever the RMB is pressed, it should cycle through the array of materials
    if (event.button === pc.MOUSEBUTTON_RIGHT) {
        this.entity.render.meshInstances[0].material = this.materials.resource;
    }
};

A friend of mine was able to help solve the problem!

//Whenever the RMB is pressed, it should cycle through the array of materials
    if (event.button === pc.MOUSEBUTTON_RIGHT) {
        //this.entity.render.meshInstances[0].material = this.materials.resource;
**this.changeToNextMaterial();**
    }

Hopefully, this helps anyone who has been going through the same problem as me.