Event when a material has been changed


#1

I want to detect if any material of my entity has been changed and call a function.
So some how I have to add a listener to the material slot.
Any ideas?


#2

Could you listen to the action that the changes the material in the first place? Does it have to this low level?

There’s no event to listen to when the material on a mesh instance is changed. You would have to monkey patch one in: https://github.com/playcanvas/engine/blob/master/src/scene/mesh.js#L375

What’s the context for needing a listener for when the material is changed?


#3

Ok, here is the context for my needs:
I’m implementing a product configurator where I have a generic and reuseable color selector button where I can switch the material for a selected (attached) object. It works fine.
In one the products I have the special case, that by switching the material of one element, another element of a more complex model should switch the material too. And (this is the important part) I can not use the same materials for both, cause of an occulsion map, which is special for each object.
This would be easy to solve if my second object could simple detect the material change of my first object by script.
I simple don’t want to write a “special” color selector class for this single use case that fires events to something or has further material slots for this special object.
colorselector

Is my issue understandable?


#4

I’m not seeing the reason why you can’t fire the event at the point the configurator changes the material on the model and pass the data needed.

You mention that the materials have to be different per model but I can’t see that being a problem?

Is the configurator changing the material on the model and you want another script to listen to event to change it to the correct material for that model?


#5

The reason is just cause of structure. It’s a bigger project and I don’t want to touch and change the integrity of components. So I was searching for a general solution that does not effect the already exiting and tested components. This change listener was just and idea, to solve this very easily. But of course I can handle it in a different way.
Right now, I’m adding a callback function to the color selector elements which can be customized by an attribute. This should work and maybe cover other “special” cases too. At least I hope so :wink:

DrawColorselector.attributes.add('clickCallback', {type: 'string', title:'Fire Event onClick'});
...
//fire callback on click
if(this.clickCallback){
    this.app.fire(this.clickCallback);
}

#6

The way I would handle it is for the configurator to fire an event (if it doesn’t already) with the material/color that it wants the material to change to.

Then have the special model or an external script listen to the event and change it to the special material based on the color passed in the event.

Your solution (the inverse of mine) would work too.