I’m trying to add a material to an object, if the material name already exists but isn’t assigned, have it assign that material while deleting any other slots. I just want that assigned material.
Here is what I have right now, it works but I would like to have a cleaner way of doing this.
import bpy
ob = bpy.context.active_object
# Delete all materials
C = bpy.context
for i in range(0,len(C.object.material_slots)):
C.object.active_material_index = 0
bpy.ops.object.material_slot_remove()
# Get material
mat = bpy.data.materials.get("rustymetal")
#if it doesnt exist, create it.
if mat is None:
# create material and assign
mat = bpy.data.materials.new(name="rustymetal")
ob.data.materials.append(mat)
#Remove all materials again, material already exists, so it can be linked.
for i in range(0,len(C.object.material_slots)):
C.object.active_material_index = 0
bpy.ops.object.material_slot_remove()
#otherwise
else:
#get material
mat = bpy.data.materials.get("rustymetal")
#assign material
ob.data.materials.append(mat)