Post #4782: Good morning @mcjamall07 and @Nanomanpro

πŸ“‹ Metadata

🏷️ Tags

macro python-scripting intermediate solved

  • Macro Editor
  • Python Scripting

πŸ’¬ Content

Good morning @mcjamall07 and @Nanomanpro

To perform operations on multiple objects at once, you can use bpy.context.selected_objects , which returns a list of all currently selected objects.

imageimage1110Γ—382 86.7 KB

# The first three objects in the list of selected objects each have a value set.
bpy.context.selected_objects[0].color[3] = value
bpy.context.selected_objects[1].color[3] = value
bpy.context.selected_objects[2].color[3] = value

# A for loop sets a value for all selected objects. 
for obj in bpy.context.selected_objects:
    obj.color[3] = value

# This uses list comprehension notation to achieve the same result in a more concise manner.
[o.color.__setitem__(3, value) for o in bpy.context.selected_objects]

# In summary, all three scripts set the value of color[3] for the selected objects. 
# However, while the first script targets only the first three objects, the latter two target all selected objects.

This method assumes that all objects have a color attribute. If any of the selected objects do not have a color attribute, an error may occur.

Furthermore, it’s difficult to retrieve values from multiple objects because when multiple objects are selected, their color[3] values may differ. Generally, we refer to the value of the active object.


To address potential issues, I’ve added a simple error handling measure that limits processing to Mesh objects.

After careful consideration, I propose two methods.

The first one involves using the Poll method to ensure that the active object is a MESH. In this case, you can use the following scripts:

imageimage710Γ—190 23.8 KB

# Getter
return bpy.context.active_object.color[3]
# Setter
[o.color.__setitem__(3, value) for o in C.selected_objects if isinstance(o.data, T.Mesh)]

Next, I propose a method that does not function at all if the active object is not a MESH. For this case, you can use these scripts:

# Getter
return C.active_object.color[3] if C.active_object and isinstance(C.active_object.data, T.Mesh) else 0.0
# Setter
[o.color.__setitem__(3, value) for o in C.selected_objects if isinstance(o.data, T.Mesh)] if C.active_object and isinstance(C.active_object.data, T.Mesh) else None

❀️ 4 likes


πŸ”— View on Blender Artists