Blender 数据可以通过两种方式来访问,一种是从当前项(context)访问,一种是从数据库访问(data)
两种方法各有各的用途和优势。
值得注意的是,大多操作符也要在正确的context下才能够运行

例子1 获取物体位置

Context

获取当前激活物体
obj = bpy.context.active_object
获取其的位置
loc = obj.location
如果直接输出obj,则会返回物体的数据库形式
bpy.data.objects['物体名字']

Data

如果你一开始就有该物体的名字,那你可以直接从数据库获取,因为名字是唯一的
obj = bpy.data.objects.get('物体名字')
这里需要考虑物体被删除,不存在的情况。如果一定存在(比如是从物体传递过来的名字),则不用考虑
if obj is not None: loc = obj.location

例子2 获取节点树

Context

从界面获取

  1. nt = None
  2. # 判断当前界面是否是节点编辑器(是否有节点数属性)
  3. if hasattr(bpy.context.space,'node_tree'):
  4. nt = bpy.context.space_data.edit_tree

Data

从数据直接获取

  1. nt = bpy.data.node_groups.get('节点树名字')

Dependant

从依赖项获取

  1. obj = bpy.context.active_object
  2. mat = nt = None
  3. # 从物体材质槽获得
  4. if obj.material_slot[0].material is not None:
  5. mat = obj.material_slot[0].material
  6. # 从材质获取材质节点树
  7. if mat:
  8. nt = mat.node_tree