Using the material plugin to report an error

I have a function button, when I click it, apply a custom material plugin, but it occurs error.

Uncaught The plugin "SnowCover" can't be added to the material "shipmtl" because this material has already been used for rendering! Please add plugins to materials before any rendering with this material occurs.

If I get you right, you try to use RegisterMaterialPlugin after you click on a button? This will not work as Docs says:

RegisterMaterialPlugin only adds the plugin to material instantiated AFTER the registration. So it must be run before you add any meshes or create your materials or they won't have the plugin.

So you will have to register the plugin to materials before you instantiate the materials.

I would just go for the approach of the Docs, showing how to create material plugins with enable/disable capability:

When I click, I add the material plugin to each material,

btn.onClick=e=>{
for(const mtl of scene.materials){
mtl.plugin=new MaterialPlugin(mtl)
}

  1. Register the factory function for the materials
BABYLON.RegisterMaterialPlugin("BlackAndWhite", (material) => {
  material.plugin = new BlackAndWhitePluginMaterial(material);
  return material.plugin;
});
  1. Then toggle isEnabled in callback of click observer
for(const material of scene.materials){
  material.plugin.isEnabled = !material.plugin.isEnabled
}

Here the full PG, just click into the scene and observe button color:

1 Like

If I add a new material, will the RegisterMaterialPlugin be automatically registered?

Yes.

If you want to avoid plugins to be registered for certain materials:

var unwantedMaterials = ["materialName5", "materialName7"]
BABYLON.RegisterMaterialPlugin("BlackAndWhite", (material) => {
  if(unwantedMaterials.indexOf(material.name) == -1)  { // not add plugin for blacklisted material names
    material.plugin = new BlackAndWhitePluginMaterial(material);
    return material.plugin;
  }
});