3
$\begingroup$

How to add material to selected objects via python? Material must be linked to Object (not Data).

$\endgroup$
0

1 Answer 1

5
$\begingroup$

If you hover your mouse over a button, it will often tell you the python binding that can be used to invoke similar actions to the button. In this case: Hovering over change link buttons

So first you assign it a material, and then go and, from the object, change the data link.

To set all materials to 'object' for a single material:

obj = an_object
for mat_slot in obj.material_slots:
    mat = mat_slot.material
    mat_slot.link = 'OBJECT'
    mat_slot.material = mat

I am not sure why re-assigning the material is necessary, but hey, it works!

To set a single material slot (untested):

obj = an_object
mat = a_material
mat_slot = [m for m in obj.material_slots if material_slot.material == mat][0]
mat = mat_slot.material
mat_slot.link = 'OBJECT'
mat_slot.material = mat

To assign a material, something like this could be written (untested):

def applyMaterial(obj, mat, mat_slot=0):
    obj.material_slots[mat_slot].link = 'OBJECT'
    obj.material_slots[mat_slot].material = mat
$\endgroup$
1
  • $\begingroup$ thank you. It works great. I need to change several materials (but not all) of the scene which is a copy of another (New Scene - Link Objects). I decided to change it using the script :) Of course, first I used U - Object $\endgroup$
    – majk
    May 23, 2016 at 9:37

You must log in to answer this question.

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