Dev:Py/Scripts/Cookbook/Materials/Multiple Materials

提供: wiki
< Dev:Py‎ | Scripts‎ | Cookbook‎ | Materials
移動先: 案内検索

Multiple materials on a Mesh

How to apply two material to the same mesh. Test it on default cube (must be selected)

# Blender 2.5
# API 36403

# Note this script creates Blender Internal materials
# it doesn't deal with material/slot removal
# running it several times in a row will create new ones


import bpy


# Definition of the first material
# Only diffuse shader is set
def MakeMaterial_1():
    mat = bpy.data.materials.new("Mat1")
    mat.diffuse_shader = 'MINNAERT'
    mat.diffuse_color = (0.0, 0.288, 0.0)
    mat.darkness = 0.8
    return mat


# Definition of the second material
def MakeMaterial_2():
    mat = bpy.data.materials.new("Mat2")
    mat.diffuse_shader = 'MINNAERT'
    mat.diffuse_color = (0.288, 0.0, 0.0)
    mat.darkness = 0.8
    return mat


# Vertices that I will assign to the vertex group
MyVertices = [2, 5, 6, 1]

obj = bpy.context.object

# ###############################################
# Assign first material on all the mesh
# ###############################################

# Add a material slot
bpy.ops.object.material_slot_add()

# Assign a material to the last slot
obj.material_slots[obj.material_slots.__len__() - 1].material = MakeMaterial_1()

# Go to Edit mode
bpy.ops.object.mode_set(mode='EDIT')

# Select all the vertices
bpy.ops.mesh.select_all(action='SELECT')

# Assign the material on all the vertices
bpy.ops.object.material_slot_assign()

# Return to Object Mode
bpy.ops.object.mode_set(mode='OBJECT')

# ###############################################
# Assign second material on vertex group
# ###############################################

# Create a Vertex Group
Group1 = obj.vertex_groups.new('MyVertexGroup')

# Add the vertices to the vertex group
# with Weight = 1.0 The Weight isn't
# relevant in this case
Group1.add(MyVertices, 1.0, 'ADD')

# Select the vertex group
bpy.ops.object.vertex_group_set_active(group='MyVertexGroup')

# Add a material slot
bpy.ops.object.material_slot_add()

# Assign a material to the last slot
obj.material_slots[obj.material_slots.__len__() - 1].material = MakeMaterial_2()

# Toggle to edit mode
# The second way to change it
bpy.ops.object.editmode_toggle()

# Deselect all the vertices
bpy.ops.mesh.select_all(action='DESELECT')

# Select the vertices of the vertex group
bpy.ops.object.vertex_group_select()

# Assign the material on the selected vertices
bpy.ops.object.material_slot_assign()

bpy.ops.object.editmode_toggle()  # Toggle to object mode