Changing Assigned Material Based on Texture Displayed in Textured View

OK so here’s the problem: When you have an object in blender that you are uv-texturing, it’s nice to assign a texture to it using the uv editing panel so you can see it in textured view. But this doesn’t correspond to the material you have assigned it. (I hope that this will change in a future release of blender, I hear the “uv face select” mode is out for good :yes:) So I try writing a little script that will change the assigned material (the “materialIndex” property) based upon the “image” property of each face. I can query both of these just fine, but when I try setting materialIndex it doesn’t change at all. Here is some (very) simplified code that highlights the problem:

import Blender
from Blender import *

for object in Blender.Object.GetSelected():
    for face in object.data.faces:
        face.materialIndex=2
    object.data.update()

Now one would expect that upon running this code, the materialIndex of each face would change to 2. It doesn’t change at all. Am I such a noob that I have missed something blindingly obvious? :spin:

You missed a small thing: the data property is readonly and returns a NMesh. Instead you’d better use getData() which returns a Mesh. The code will look like this:

import Blender
from Blender import *

for object in Blender.Object.GetSelected():
    for face in object.getData(False,True).faces:
        face.mat=1
Blender.Redraw()

Note: the second material in the list has index 1, as the first material in the list has index 0.

Bah knew I was a noob :stuck_out_tongue: Thank you!

I already wrote a script that does just this… and back again
http://blenderartists.org/forum/showthread.php?t=115948