# return the original materials with python

I have an object with three materials (mat 1 mat2, mat3). with python I want to apply another material (mat4) to my object and return to the initial state (mat1, mat2, mat3). is it possible ? I have to save the list of starting materials to apply them or there are more simple?

• I would write a function that retrieves each face and sets proper material, another function will select all faces and apply the other material. Then you call your functions (fist, second, first). You need to create one object (as python object) per material 'mat1 = bpy.data.meshes['MeshName'].materials['MaterialName']' so that you can apply it to the mesh: bpy.data.meshes[MeshName].vertices[index] = mat1 – Yvain Mar 31 '16 at 11:16

You can keep the original material index in a mesh.polygon_layers_int layer. Or save the material name in a polygon_layers_string As shown in sample code below.

import bpy
context = bpy.context
scene = context.scene

obj = context.object
mesh = obj.data

save_mat_layer = mesh.polygon_layers_int.get('material_index')
if save_mat_layer is None:
save_mat_layer = mesh.polygon_layers_int.new(name='material_index')

save_matname_layer = mesh.polygon_layers_string.get('material_name')
if save_matname_layer is not None:
save_matname_layer = mesh.polygon_layers_string.new(name='material_name')

for f in mesh.polygons:
save_mat_layer.data[f.index].value = f.material_index
save_matname_layer.data[f.index].value = mesh.materials[f.material_index].name.encode()


PS: not sure if obtaining desired result for the string layer.