The following:
bpy.data.objects['Cube'].select = True
bpy.context.scene.objects.active = bpy.data.objects['Sphere.017']
don't work in Blender 2.8, they did in 2.79 though.
How should I select (multiple) objects with Python in Blender 2.8?
The following:
bpy.data.objects['Cube'].select = True
bpy.context.scene.objects.active = bpy.data.objects['Sphere.017']
don't work in Blender 2.8, they did in 2.79 though.
How should I select (multiple) objects with Python in Blender 2.8?
According to the API changes:
In 2.7x, you could directly (de)select an Object from its select property. This has been removed in 2.8x, in favor of some get/set functions.
bpy.data.objects['Cube'].select = True # 2.7x
bpy.data.objects['Cube'].select_set(True) # 2.8+
Proof using the Console:
>>> bpy.context.scene.objects["Cube"].select_set(True)
>>> bpy.context.scene.objects["Cube"].select_get()
True
API Link: docs.blender.org/api/current/bpy.types.Object.html#bpy.types.Object.select_set
Example on how to select a certain object in the scene and make it the active object:
ob = bpy.context.scene.objects["Cube"] # Get the object
bpy.ops.object.select_all(action='DESELECT') # Deselect all objects
bpy.context.view_layer.objects.active = ob # Make the cube the active object
ob.select_set(True) # Select the cube
Example on how to select multiple objects by name:
for o in ("Cube", "Camera", "Light"):
obj = bpy.context.scene.objects.get(o)
if obj: obj.select_set(True)
Example on how to select all objects of a certain collection:
col = bpy.data.collections.get("Collection")
if col:
for obj in col.objects:
obj.select_set(True)
adding thoses two lines work in 2.79, but not in 2.80
bpy.context.scene.objects.active = OB
OB.select = True
the api has change for this new version, so for 2.8 its
bpy.context.view_layer.objects.active = OB
OB.select_set(state=True)
so now my correct code is this
import bpy
OB = bpy.context.selected_objects[0]
bpy.ops.object.modifier_add(type='MIRROR')
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.empty_add(type='PLAIN_AXES', view_align=False, location=(bpy.context.scene.cursor_location))
OA = bpy.context.selected_objects[0]
bpy.context.object.name = "Mirror Axes"
OB.modifiers["Mirror"].mirror_object = bpy.data.objects["Mirror Axes"]
OB.select_set(state=True)
bpy.context.view_layer.objects.active = OB
OA.select_set(state=False)
open_menu("D Mirror Menu")
The line bpy.context.object = OB
throws an exception. Context property "object" is read-only.
In 2.79 and below, we can set the scene's active object with the scene's property:
bpy.context.scene.objects.active = OB