说明

blender插件脚本里新建物体的两种方法,其实本质上是一样的,这里做个记录以防日后忘记。

方法一

来自之前在网络上搜到的方法,是直接在data里新建物体并link到场景集合里。

class PointsImport(bpy.types.Operator):
    bl_idname = 'obj.import_points'
    bl_label = '导入点云'
    bl_options = {'REGISTER', 'UNDO'}

    name: bpy.props.StringProperty(default='points')
    path: bpy.props.StringProperty(subtype='FILE_PATH')

    def execute(self, context):
        points = np.load(self.path)
        verts = []
        for i in points:
            verts.append(tuple(i))

        # 新建mesh
        mymesh = bpy.data.meshes.new(self.name)
        mymesh.from_pydata(verts, [], [])
        mymesh.update()

        # 新建object并添加到场景
        myobject = bpy.data.objects.new(self.name, mymesh)
        bpy.context.scene.collection.objects.link(myobject)

        self.report({'INFO'}, f'import {len(points)} points')
        return {'FINISHED'}

方法二

来自blender自带的demo,直接调用了object_data_add方法,是更正规的方法,需要注意的是需要继承AddObjectHelper

import bpy
from bpy.types import Operator
from bpy.props import FloatVectorProperty
from bpy_extras.object_utils import AddObjectHelper, object_data_add
from mathutils import Vector

def add_object(self, context):
    scale_x = self.scale.x
    scale_y = self.scale.y

    verts = [
        Vector((-1 * scale_x, 1 * scale_y, 0)),
        Vector((1 * scale_x, 1 * scale_y, 0)),
        Vector((1 * scale_x, -1 * scale_y, 0)),
        Vector((-1 * scale_x, -1 * scale_y, 0)),
    ]

    edges = []
    faces = [[0, 1, 2, 3]]

    mesh = bpy.data.meshes.new(name="New Object Mesh")
    mesh.from_pydata(verts, edges, faces)
    # useful for development when the mesh may be invalid.
    # mesh.validate(verbose=True)
    object_data_add(context, mesh, operator=self)


class OBJECT_OT_add_object(Operator, AddObjectHelper):
    """Create a new Mesh Object"""
    bl_idname = "mesh.add_object"
    bl_label = "Add Mesh Object"
    bl_options = {'REGISTER', 'UNDO'}

    scale: FloatVectorProperty(
        name="scale",
        default=(1.0, 1.0, 1.0),
        subtype='TRANSLATION',
        description="scaling",
    )

    def execute(self, context):

        add_object(self, context)

        return {'FINISHED'}
最后修改:2020 年 12 月 08 日 03 : 55 PM