Hello, I’m trying to change material of an object every frame, but i want it to work only for an active object but my script changes it for every object , how can I fix it?
# Import the bpy module
import bpy
# Get a reference to the active object in the scene
obj = bpy.context.view_layer.objects.active
# Create an empty list to store the materials
materials = []
# Iterate over all of the materials assigned to the object
for material_slot in obj.material_slots:
# Add each material to the list
materials.append(material_slot.material)
# Set the current index to 0
current_index = 0
# This function will be called after every frame update
def switch_material(scene):
global current_index
# Switch to the next material in the list
current_index = (current_index + 1) % len(materials)
obj.active_material = materials[current_index]
# Register the function to be called after every frame
bpy.app.handlers.frame_change_post.append(switch_material)
P.S this script was created by openai, I have zero knowledge of python
# Import the bpy module
import bpy
# Define a list of objects to cycle the materials for
object_names = ['Object1', 'Object2', 'Object3']
# Create a dictionary to store the materials for each object
materials = {}
# Iterate over the objects in the list
for obj_name in object_names:
# Get a reference to the object
obj = bpy.data.objects[obj_name]
# Create an empty list to store the materials for this object
materials[obj_name] = []
# Iterate over all of the materials assigned to the object
for material_slot in obj.material_slots:
# Add each material to the list
materials[obj_name].append(material_slot.material)
# Set the current index to 0 for each object
current_indexes = {}
for obj_name in object_names:
current_indexes[obj_name] = 0
# This function will be called after every frame update
def switch_material(scene):
global materials, current_indexes
# Iterate over the objects in the list
for obj_name in object_names:
# Get the current index for this object
current_index = current_indexes[obj_name]
# Get a reference to the object
obj = bpy.data.objects[obj_name]
# Switch to the next material in the list
current_index = (current_index + 1) % len(materials[obj_name])
obj.active_material = materials[obj_name][current_index]
# Update the current index for this object
current_indexes[obj_name] = current_index
# Register the function to be called after every frame
bpy.app.handlers.frame_change_post.append(switch_material)
thank you! you could also ask it to simplify the code afterwards, but i don’t know how good the result is. You should try it with your code or something maybe it will be useful to you.