Assign materials to individual faces

I’m trying to change the material assigned to certain faces.

I thought that bpy.data.objects[…].data.polygons[…].material_index would do the trick, but this property seems revert back to its original value as soon as I switch out of edit mode (bpy.ops.object.model_set(mode=“OBJECT”)).

I’m assuming that polygons and faces are the same thing here.

Try doing it in object mode instead of edit mode.

(Also, take my advice with a grain of salt. I’m new and have no idea if that would be bad practice, but it seems to work.)

the “old” API requires mode switching, you have to be in object mode or basically nothing will work.

If you wanna avoid that, use the bmesh module.

@Kopachris lol Indeed, that does work. I’m not sure I’ll ever get my head wrapped around Blender’s API.

@CoDEmanX Thanks. I was specifically switching in to edit mode because I thought I needed to do that.

The material slots must exist with a valid material before you can use the material index on a polygon/face. Perhaps that is why they are reverting back? Does the mesh have multiple materials before you enter edit mode?

Yes, the materials are available. Everything works fine if I skip the Object–>Edit–>Object mode change.

I suspect that edit mode makes a copy of the object’s state, makes edits to that copy, and then writes it’s copy back to the object upon switching back to object mode. In this case, that write would overwrite the changes I made. But that is just my guess as to what is going on.

Hi there,
I just wrote a little addon that does just that, assigns face materials randomly (out of the list of available materials on the mesh object).

It uses bmesh, which is simpler and works consistenly in BI and Cycles. Here’s the code if you’re interested (just to the function “randomize” in the class “rand_mat_assigner” to see the relevant code).

I’m also explaining it in a blogpost here.