Override all excisting materials temporarily in the scene with another material

I have made a button that assigns a specific material (nodetree of 9 nodes) to a selected object. But now i would like to have this button (that is the operator for the material), overrides all other existing materials in the scene, except for 1 object (for example named ‘Plane’). So when the button is pushed the material would be set on all objects with materials, except the object called ‘plane’.
And if possible that there is also a way to go back to the materials before using the button ( a restore function).
Anyone has experience with this? Any tutorials. Thanks

A rough proof-of-concept to get you started:

import bpy

view_layer = bpy.context.view_layer
objects = view_layer.objects

obj_mat_mapping = {}
for obj in objects:
    # Ignore selected objects
    if obj.select_get(view_layer=view_layer):
    obj_mat_mapping[obj] = [slot.material for slot in obj.material_slots]
# Apply override mat
override_mat = bpy.data.materials["override"]
for obj in obj_mat_mapping.keys():
    for slot in obj.material_slots:
        slot.material = override_mat
# Restore materials
for obj, old_mats in obj_mat_mapping.items():
    for i in range(len(old_mats)):
        obj.material_slots[i].material = old_mats[i]

Some notes for production use:

  • Think about undo/redo and how they might screw up this workflow
  • Don’t use object/material references in persistent lists/dicts in production, they can change in several cases (e.g. undo) and then the script will crash. Instead, use the object/material names. Beware of name collisions (when linking stuff from libraries, the names can be the same, so construct a unique key). You’ll also need to handle the case that the user has renamed an object or material.
  • The user might have removed or added material slots between override and restore. Add code to handle this case

Thanks, i try to make it work with this. Not sure where to put this into my code but hey, we are still learning every day.
Thank you for the work you put into this.