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


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
    # no slots
  • $\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$ – binaryBigInt Jan 19 '15 at 13:13
  • 1
    $\begingroup$ Yes, it is also possible to manipulate the material nodes with python, but that is for another question $\endgroup$ – Jaroslav Jerryno Novotny Jan 19 '15 at 13:15
  • 1
    $\begingroup$ Amazing. These sanity checks actually helped me understand how the things work a lot! $\endgroup$ – Sibbs Gambling Nov 17 '16 at 19:17

"Is it also possible to specify which material (glossy, glass, diffuse)" I don't think this is "another question" because if you do the code above you are working with the principled BSDF added by default but after several researches I found an answer working in blender 2.8 there Add Nodes to Material with Python. you have to work with nodes or you don't really see on what you are working.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.