1

I wish to edit a component of an object, say a cube, using python script.

For example if I need to change the material or color of just one face of the cube/object, can I do that using python?

David
  • 49,291
  • 38
  • 159
  • 317
iamkhush
  • 305
  • 2
  • 11
  • Related http://blender.stackexchange.com/questions/6409/repetitive-tasks-using-python/6410#6410 http://blender.stackexchange.com/questions/8475/python-set-material-to-material-slot – stacker Nov 05 '14 at 17:05
  • here is another link that does random materials, but you could change that to use one material http://bioblog3d.wordpress.com/2013/01/30/random-meshface-material-assigner/ – BlendingJake Nov 05 '14 at 17:12
  • Yes, you can do that via python. – Vader Nov 05 '14 at 18:31

1 Answers1

1

Yes, you can. You will need a second material and then assign that material to the face. Here is an example I concocted which affects the faces you have selected in EDIT mode:

import bpy
import bmesh

def get_other_material():
    mat = bpy.data.materials.get("pants")
    if mat is None:
        mat = bpy.data.materials.new("pants")
        mat.diffuse_color = (0.8, 0.6, 0)
    return mat

def setPolyMaterial(obj, polyIdxs):
    if len(obj.data.materials)<2:
        obj.data.materials.append(get_other_material())
    material_index = 1

    if bpy.context.mode == 'EDIT_MESH':
        bm = bmesh.from_edit_mesh(obj.data)    
        for idx in polyIdxs:
            bm.faces[idx].material_index = material_index
        bmesh.update_edit_mesh(obj.data)
    else:
        for idx in polyIdxs:
            obj.data.polygons[idx].material_index = material_index

obj = bpy.context.active_object
if bpy.context..mode == 'EDIT_MESH':
    bm = bmesh.from_edit_mesh(obj.data)
    polyIdxs = [ f.index for f in bm.faces if f.select ]
else:
    polyIdxs = [ p.index for p in obj.data.polygons if p.select ]
setPolyMaterial( obj, polyIdxs)

I personally prefer to avoid anything from bpy.ops if I can because it requires you to mess with the editor state; and exactly what state you must adjust is entirely undocumented (although usually straightforward, USUALLY).

If you want to alter anything other than the diffuse_color, you can hover your mouse over the field and a pop-up will usually appear giving you an indication of the path to that property in python code (although sometimes it is truncated and you have to go to #blenderpython for an answer)

Mutant Bob
  • 9,243
  • 2
  • 29
  • 55