这个错误是由于运行脚本时的上下文环境不正确导致的。在Blender中,许多操作需要特定的上下文环境才能正常工作。您可以尝试将以下代码添加到您的脚本中,以确保正确的上下文环境:
# 设置上下文环境
bpy.context.area.type = 'VIEW_3D'
bpy.context.space_data.viewport_shade = 'SOLID'
# 选择和激活场景对象
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete()
# 添加一个Cube对象作为空间范围
bpy.ops.mesh.primitive_cube_add(size=2)
# 添加一个Sphere对象作为模板
bpy.ops.mesh.primitive_uv_sphere_add(radius=0.1, location=(0, 0, 0))
# 创建一组球体并随机分布在空间范围内
for i in range(100):
x = random.uniform(-1, 1)
y = random.uniform(-1, 1)
z = random.uniform(-1, 1)
# 激活复制前面创建的球体
bpy.ops.object.select_all(action='DESELECT')
bpy.data.objects['Sphere'].select_set(True)
bpy.context.view_layer.objects.active = bpy.data.objects['Sphere']
# 复制球体并设置位置
bpy.ops.object.duplicate()
obj = bpy.context.active_object
obj.location = (x, y, z)
# 连接距离小于1厘米的球体
spheres = [obj for obj in bpy.data.objects if obj.name.startswith('Sphere')]
for i, sphere1 in enumerate(spheres):
for j, sphere2 in enumerate(spheres[i+1:]):
dist = (sphere1.location - sphere2.location).length
if dist < 0.01:
bpy.ops.object.select_all(action='DESELECT')
sphere1.select_set(True)
sphere2.select_set(True)
bpy.ops.object.join()
这里我们添加了设置上下文环境的代码,并使用bpy.context.view_layer.objects.active
激活之前创建的球体对象,以便正确地进行复制操作。