Get Blender X,Y,Z and Bounding Box with script

I need to get the x,y,z values of an object as well as the bounding box through a script. So far I have the area and volume with the following code:

bm = bmesh.new()
bm.from_object(bpy.context.object, bpy.context.scene)
area = str(sum(f.calc_area() for f in bm.faces))
volume = str(bm.calc_volume())


I tried something like this for the bounding box:

bb = str(bm.dimensions())


or

bb = bpy.data.objects["test2-2"].dimensions


but neither have worked. As far as the x,y,z values go I'm stumped. Please let me know if you have any suggestions.

Thanks!

• I think you just need to specify which attribute to get from the dimensions (bpy.data.objects["test2-2"].dimensions.x for example) As for location, use bpy.data.objects["test2-2"].location.z – Greg Zaal Apr 10 '14 at 8:09
• wow, that totally makes sense, and works well. Thanks a bunch! – Alex Husarenko Apr 10 '14 at 8:53
• Wasn't sure if that's all you wanted to know - added it as an answer. – Greg Zaal Apr 10 '14 at 12:58

2 Answers

Both location and dimensions are vectors, meaning they'll return a vector of three values (x, y, z). If you want to get only one axis, use:

bpy.data.objects['object_name'].location.x
bpy.data.objects['object_name'].location.y
bpy.data.objects['object_name'].location.z


The dimensions of the bounding box of that object:

bpy.data.objects['object_name'].dimensions.x
bpy.data.objects['object_name'].dimensions.y
bpy.data.objects['object_name'].dimensions.z


You can set the values by simply using obj.location.x = 5, or if you would like to set all three axes, you can do obj.location = (1, 2, 3)

• If I try to use dimension.x in a driver variable, it doesn't recognize it as a valid data path. I have to write dimensions[0] to get the x value. – Max Kielland Oct 30 '14 at 19:31

To include parenting and drivers, use this for the actual object location / origin:

ob = bpy.context.object

ob.matrix_world.translation # or .to_translation()


You can get the bounding box corners Object.bound_box in object-space and multiply by Object.matrix_world for world-space:

bbox_corners = [ob.matrix_world * Vector(corner) for corner in ob.bound_box]


Note that the bounding box is not axis aligned.

• Starting from 2.8 TypeError: Element-wise multiplication: not supported between 'Matrix' and 'Vector' types: needs to be: bbox_corners = [ob.matrix_world @ Vector(corner) for corner in ob.bound_box] – oneiros Nov 5 '19 at 18:14