Is it possible to use the bpy.ops.constraint.apply(constraint="Copy Transforms", owner='OBJECT')
on a specified object instead of the default behavior of it working only on the active object ? Someone told me that i can override the context for that but i can't really find any tutorials on it and i'm too inexperienced with coding to understand the documentation. Would highly appraciate any help. I don't want to make the named object an active one, i need the behavior to be something like bpy.data.objects['ObjectName'].constraints.new(type='COPY_TRANSFORMS')
$\begingroup$
$\endgroup$
0
Add a comment
|
2 Answers
$\begingroup$
$\endgroup$
3
You don't have to set the object as active in order to apply the constraint.
for obj in bpy.context.selected_objects:
# loop over the constraints in each object
for con in obj.constraints[:]:
# get the constraint you want to apply
if con.type == "COPY_TRANSFORMS":
# apply it using the constraint name.
bpy.ops.constraint.apply(constraint=con.name)
It's the same process for modifiers as well.
-
$\begingroup$ How to apply this script to bones? $\endgroup$ Commented Nov 27, 2022 at 6:21
-
$\begingroup$ off the top of my head i'm pretty sure you would just change it to
bpy.context.selected_pose_bones
instead of selected objects. YMMV. $\endgroup$– JakemoyoCommented Dec 3, 2022 at 12:08 -
$\begingroup$ "You don't have to set the object as active in order to apply the constraint." - just checked and yes you do. Otherwise how would the operator know which constraint to apply, if multiple constraints had the same name? Also, you will get an error if there is no active object.
RuntimeError: Operator bpy.ops.constraint.apply.poll() Context missing active object
$\endgroup$ Commented Jan 15, 2023 at 1:08
$\begingroup$
$\endgroup$
Adapting Jakemoyo's code:
import bpy
from bpy import context as C, data as D
for ob in C.selected_objects:
to_apply = [c.name for c in ob.constraints if c.type=='COPY_TRANSFORMS']
if not to_apply:
continue
with C.temp_override(object=ob):
for constraint_name in to_apply:
bpy.ops.constraint.apply(constraint=constraint_name)