Blender python cookbook
Consider installing this addon:
http://code-autocomplete-manual.readthedocs.io/en/latest/setup.html#installation
Iterate scene
for obj in bpy.context.scene.objects:
print(obj.name)
Iterate selection, check type
for obj in bpy.context.selected_objects:
if obj.type == 'MESH':
print(obj.name, 'is mesh')
Get object by name
scene.objects.get('Camera')
Deselect:
bpy.ops.object.select_all(action='DESELECT')
Select
obj.select_set(True)
Blend location:
bpy.path.abspath("//")
Mesh level:
#.vertices
#.polygons
for obj in bpy.context.selected_objects:
for vert in obj.data.vertices:
vert.select = True
vert_pos_x = vert.co.x
Delete:
This took me longer to figure out than it should've:
bpy.data.objects.remove(object)
Driver with custom properties:
# car has a door_open property (0-1)
bpy.data.objects['car']['doors_open']*90
Animations:
a = object1.animation_data.action
# you can then assign that action
object2.animation_data.action = a
# if that object is not animated, use
object2.animation_data_create()
Hierarchy:
object.parent
object.children
Khronos GLTF export:
bpy.ops.export_scene.gltf(filepath='file.gltf', export_selected=True, export_apply=True)
OBJ export
bpy.ops.export_scene.obj('file.obj', check_existing=False, use_selection=True)
Get material name
for slot in obj.material_slots:
print slot.name
# it's own vector class is in mathutils.
vec = mathutils.Vector((1.0, 2.0, 3.0))
Enter edit mode
for obj in bpy.context.selected_objects:
bpy.context.scene.objects.active = obj
bpy.ops.object.mode_set(mode='EDIT')
Batch export (or everything else, really)
blender <path_to_blend.blend> --background --python <path_to_python_script.py>
Example script doing a gltf export to the folder where your .blend is (YMMV)
import bpy
import os
dest_file = "out.gltf"
blend_file_dir=bpy.path.abspath("//")
target_path = os.path.join(blend_file_dir, dest_file)
print('Exporting to', target_path)
bpy.ops.export_scene.gltf(filepath=target_path)