Changing active_object

It seems that a lot of what I want to do with scripting requires me to switch the active_object to another while iterating on an arbitrary selection of objects. Is there a sort of “standard” way to approach this that would work in a number of scenarios? Thanks for your help.


bpy.ops.object.select_pattern(pattern="ObjName")
bpy.context.scene.objects.active = bpy.data.objects["ObjName"]

Do you really need to iterate over objects by actually selecting them or setting them as the active object? Can you find a lower-level operation for what you’re trying to do?

Sometimes I have to select objects as well, in order to perform some action, such as when you simply have to call a bpy.ops. But there might be an easier way to accomplish what you’re trying to do.

If all else fails, you can simply iterate through the scene objects, deselecting them, then select your desired object and setting the active object to that one as well.


obj = scene.objects[object_name]
for ob in scene.objects:
    ob.select = False
obj.select = True
scene.objects.active = obj
...

Thanks for the replies.
@skywola
I’m not sure what your first line of code is doing but the second line looks like it might be fine for most things I’m doing. (I tried all kinds of similar combinations that didn’t work)

@ ohsnapitsjoel,
I’m new to python and scripting in Blender so I’m sure that there is a better way to do the things I want to do but I don’t know them yet! :slight_smile: Thanks for your suggestions I will try and think of my problem in a different way.