6

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
ideasman42
  • 47,387
  • 10
  • 141
  • 223
aditia
  • 970
  • 9
  • 18

2 Answers2

10

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.

Adhi
  • 14,310
  • 1
  • 55
  • 62
1

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.

ideasman42
  • 47,387
  • 10
  • 141
  • 223