MaterialSwitcher It works on primitives, but does not work on mesh objects, please help
All buttons and materials are named correctly.
var MaterialSwitcher = pc.createScript(‘materialSwitcher’);
// initialize code called once per entity
MaterialSwitcher.prototype.initialize = function() {
var materialNames = [ ‘Wood’, ‘Stone’, ‘Tiles’ ];
materialNames.forEach(function (name) {
// Get the button entity for the given material name
var buttonEntity = this.app.root.findByName(name + ' Button');
// When the button is clicked, replace the material on the model
buttonEntity.button.on('click', function () {
var material = this.app.assets.find(name, 'material').resource;
this.entity.model.material = material;
}, this);
}.bind(this));
};
Hi @vladGvlad and welcome!
For mesh objects you need to apply the material on each mesh instance, like this:
this.entity.model.meshInstances.forEach( function(meshInstance){
meshInstance.material = material;
});
Does not work
var MaterialSwitcher = pc.createScript(‘materialSwitcher’);
// initialize code called once per entity
MaterialSwitcher.prototype.initialize = function() {
var materialNames = [ ‘Wood’, ‘Stone’, ‘Tiles’ ];
materialNames.forEach(function (name) {
// Get the button entity for the given material name
var buttonEntity = this.app.root.findByName(name + ' Button');
// When the button is clicked, replace the material on the model
buttonEntity.button.on('click', function () {
var material = this.app.assets.find(name, 'material').resource;
this.entity.model.meshInstances.forEach( function(meshInstance){
meshInstance.material = material;
});
Can you post your editor url to take a look?
So, your issue is JS related, you are using this twice on line 13 of your material-switcher.js script:
Update that to the following and it will work:
this.entity.model.meshInstances.forEach( function(meshInstance){
meshInstance.material = material;
});
Wow, yes, everything works !!! Thank you so much!!! 
1 Like