Assign New Material to Selected Faces

I thought this would be simple, but it’s getting really complicated…

I want a script where I select some faces on an object, and the script automatically assigns a new material to those faces.

The problem is that IF it’s a NEW object with no materials assigned, and I add a new slot, and then add a new material, Blender automatically assigns that first material to all the faces. But I only want a material assigned to the selected faces. So I need to add two materials, and assign the second to the selected faces?

And if it’s an existing object with multiple materials, and I select some faces, I only need to add ONE new material for those faces.

This is making my head explode. I guess I need to determine first whether the object already has materials assigned, and if not I make two new materials and assign the second one to the selected faces. But if it does have materials assigned I only make one new one and assign it.

I give up. Anyone have a reasonably simple way to do this?

Thanks.

I’m not sure quite what you’re trying to do, but would this work?

import bpy

object = bpy.context.object
if len(object.material_slots) == 0:
    bpy.ops.object.material_slot_add()
    slot = object.material_slots[object.active_material_index]
    mat = bpy.data.materials.new("My material")
    slot.material = mat

bpy.ops.object.material_slot_add()
slot = object.material_slots[object.active_material_index]
mat = bpy.data.materials.new("My material 2")
slot.material = mat
mat.diffuse_color = (1, 0, 0, 1)
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.object.material_slot_assign()
bpy.ops.object.mode_set(mode='OBJECT')

WOW !!! Wonderful !!! Thanks much. I was wondering how I’d access an object’s material slots, and I was fumbling around with bpy.context.object.data.materials…

But it looks like your len(object.material_slots) will do the trick.

Thanks.

1 Like

By the way, that works perfect. Thanks again.

1 Like