40
$\begingroup$

How can I assign a new material to an object in the scene via Python?

$\endgroup$
0

1 Answer 1

86
$\begingroup$

Here you go, code with some safety checks:

import bpy
ob = bpy.context.active_object

# Get material
mat = bpy.data.materials.get("Material")
if mat is None:
    # create material
    mat = bpy.data.materials.new(name="Material")

# Assign it to object
if ob.data.materials:
    # assign to 1st material slot
    ob.data.materials[0] = mat
else:
    # no slots
    ob.data.materials.append(mat)
$\endgroup$
3
  • $\begingroup$ Thanks for your answer. Is it also possible to specifiy which material (glossy, glass, diffuse) and also the different properties (r,g,b, shinyness)? $\endgroup$ Jan 19, 2015 at 13:13
  • 2
    $\begingroup$ Yes, it is also possible to manipulate the material nodes with python, but that is for another question $\endgroup$ Jan 19, 2015 at 13:15
  • 4
    $\begingroup$ Amazing. These sanity checks actually helped me understand how the things work a lot! $\endgroup$ Nov 17, 2016 at 19:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .