Many operators act from selected objects to the active object, e.g. the parenting operator bpy.ops.object.parent_set. To use it in Python I want to change the active object to the presumed parent. The code to make the object ob active in 2.79 is simply:
context.scene.objects.active = ob
However, this does not work in 2.80 because Scene.objects does not have an active attribute. So my question is, how to change the active object in 2.80?
Scene.objects does not have a link attribute either, but in 2.80 we apparently have to link an object into a collection rather than into a scene. So the 2.79 code
to set the active object :
bpy.context.view_layer.objects.active = ob
an alternative to context.view_layer.collections.active.collection.objects.link(ob) :
bpy.context.scene.collection.objects.link(ob)
Here you link object to the scene âmaster collectionâ , itâs not in some other collection ,
it will be at the root of the scene in the outliner
Another way :
col = bpy.data.collections[âmy collectionâ]
col.objects.link (ob)
And , another way that I use to set parents without using bpy.ops :
par = bpy.context.scene.objects[âCameraâ]
ob = bpy.context.scene.objects[âCubeâ]
mat = ob.matrix_world.copy()
ob.parent = par
ob.matrix_world = mat
Even if itâs more lines of code, itâs generally better not to use bpy.ops when possible. Here you donât need to do selection whatsoever and itâs less context sensitive.
But if bpy.ops work itâs not a crime to use it.
N00b so forgive my ignorance: this seems counter intuitive to how Iâve used Python in the past, and Iâm getting errors relating to ob not being defined, even when I replace it with the name of an object being used in my file.
Do I have to set OB equal to something elsewhere?
object assignment isnât counter intuitive at all⌠you might say itâs the entire backbone of Python.
chances are, since youâre using code from a post thatâs two years old, the example is out of date and no longer works. In 2.8 there is no context.scene.objects.active anymore, so youâre probably not getting an error about âobâ not being defined, but scene.objects not having an attribute called âactiveâ. The correct 2.8 syntax is: context.view_layer.objects.active = obj