5
$\begingroup$

enter image description here

I want to iterate over the material index of material slot and change the value of each material index. How can this be done in Python?

I've tried using the Python shown below, but it doesn't work correctly.

import bpy

object = bpy.context.object
material = object.active_material
for num in range(0, 5):
    object.active_material_index = num
    if material.use_shadeless:
       material.use_shadeless = False 
    else:
       material.use_shadeless = True
$\endgroup$
9
$\begingroup$

The fastest way to loop over the object's materials is through its material_slots attribute. Here's an equivalent code for toggling all object materials shadeless property:

import bpy

for m in bpy.context.object.material_slots:
    m.material.use_shadeless = not m.material.use_shadeless

The only issue I see in your own code is that you're assigning the material to a variable before changing active material index, which renders the latter operation moot. Changing the index before assigning the resulting material to a variable, will yield the result you want.

$\endgroup$
  • $\begingroup$ this work best, using material_slots seems solve the issue $\endgroup$ – aditia Oct 16 '13 at 3:36
  • $\begingroup$ doesn't look like it works for you. maybe further testing is needed. $\endgroup$ – Adhi Oct 17 '13 at 14:11
1
$\begingroup$

The error with the script is its not re-assigning material.

Corrected script:

import bpy

object = bpy.context.object
for num in range(0, 5):
    object.active_material_index = num
    material = object.active_material  # <-- changed line
    if material.use_shadeless:
       material.use_shadeless = False 
    else:
       material.use_shadeless = True

@Adhi's method is nicer, just showing what the mistake was.

$\endgroup$
  • $\begingroup$ aahh...so I just missed one line, thanks for pointing it out Campbell. $\endgroup$ – aditia Oct 16 '13 at 3:37

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.