I read this first to get an idea on assigning materials.
How to assign a new material to an object in the scene from Python?
I wrote a script to replace one material with another. It seems to work on an active object but does not replace materials on selected objects if I loop through them. I do not know if it is because the rest of the objects are not active or there is another reason.
How do I correctly replace materials with others?
Code is posted below:
import bpy
def replace_material(object,old_material,new_material):
"""
replace a material in blender.
params:
ob - object for which we are replacing the material
old_material - The old material name as a string
new_material - The new material name as a string
"""
ob = object
om = bpy.data.materials[old_material]
nm = bpy.data.materials[new_material]
print ("ob is ",ob)
print ("om is", om)
print ("nm is", nm)
materialnum = len (ob.data.materials)
print ("materialnum is", materialnum)
for i in range(0,materialnum):
# test if the old material is in the slot and replace it
print ("running ", i)
if ob.data.materials[i] == om:
print ("match found", ob.data.materials[i])
ob.data.materials[i] == nm
def main ():
#get a list of objects selected
selected = bpy.context.selected_objects
active = bpy.context.active_object
for obj in selected:
replace_material(obj,'DEFAULT BASE','Default Base')
main()
Sample blend here: http://www.pasteall.org/blend/42037
slots = [s for s in obj.material_slots if s.material.name == old_material]
will give you a list of the material slots with old material, which you can then set withs.material = bpy.data.materials.get(new_material)
. (nb get will return None if there is no material of that name, whereas materials[name] will throw an error) $\endgroup$