2
$\begingroup$

I've been trying to do that but have got some problems:

  1. I was not able to retrieve the reference to a recently created object with bpy.ops.object.add().
    I had to use bpy.ops.lattice.select_all(), but that sounds inelegant.

  2. While I was able to create a lattice for each object with bpy.ops.object.modifier_add(type='LATTICE'), I was not able to link it - mostly because the command to link a lattice modifier to the lattice object won't show on the info window. (Also, this needs the object to be selected...)

What is the proper way to do it?

$\endgroup$

1 Answer 1

4
$\begingroup$

The proper way is to not use operators:

import bpy

scene = bpy.context.scene

lattice = bpy.data.lattices.new("Lattice")
lattice_ob = bpy.data.objects.new("Lattice", lattice)
lattice_ob.scale = (5, 5, 5)

for ob in scene.objects:
    if ob.type == 'MESH':
        mod = ob.modifiers.new("Lattice", 'LATTICE')
        mod.object = lattice_ob

scene.objects.link(lattice_ob)
scene.update()

The .new() methods return object references to be used for subsequent method calls and property assignments in contrast to operators, which run isolated and only return a status (e.g. {'FINISHED'}). Some methods also take objects (the second parameter of objects.new()), whereas operators don't support objects/pointers, but only references by name (StringProperty).

//update: For Blender 2.8 and above, I believe you would do it like this:

import bpy

collection = bpy.context.collection

lattice = bpy.data.lattices.new("Lattice")
lattice_ob = bpy.data.objects.new("Lattice", lattice)
lattice_ob.scale = (5, 5, 5)

for ob in collection.objects:
    if ob.type == 'MESH':
        mod = ob.modifiers.new("Lattice", 'LATTICE')
        mod.object = lattice_ob

collection.objects.link(lattice_ob)
$\endgroup$
4
  • $\begingroup$ insightful, thank you. Hopefully knowing that option will make it easier next time. Thanks. $\endgroup$
    – Dokkat
    Apr 8, 2014 at 19:07
  • $\begingroup$ This didn't work on 2.90 .... :(( AttributeError: 'bpy_prop_collection' object has no attribute 'link' Can it be updated? $\endgroup$ Jul 16, 2020 at 4:50
  • $\begingroup$ Added a possible solution for Blender 2.8+, but I don't know whether this is the canonical way to go about it. At least it seems like no update() call is needed anymore. Maybe object_data_add() from bpy_extras.object_utils would be better and includes a layer update. $\endgroup$
    – CodeManX
    Jul 16, 2020 at 13:01
  • $\begingroup$ bpy.data.collections['Collection'].objects.link(lattice_ob) add that line after setting the scale. $\endgroup$
    – rzaratx
    Jun 2, 2021 at 23:54

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .