Blender:Python脚本失败(创建简单运算符)

2024-09-29 23:28:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Blender中自学Python,并尝试使用脚本创建一个简单的操作符。脚本如下-它的目的是在场景中选择四个(聚光灯)并改变它们的能量(基本上是,打开和关闭灯光)。但是当我试图运行脚本时,我得到一条“Python脚本失败”的错误消息。有人能看出密码有什么问题吗?在

import bpy


def main(context):
    for ob in context.scene.objects:
        print(ob)

class LightsOperator(bpy.types.Operator):

    bl_idname = "object.lights_operator"
    bl_label = "Headlight Operator"

    @classmethod
    def poll(cls, context):
        return context.active_object is not None

    def execute(self, context):
        light1 = bpy.data.objects['headlight1']
        light2 = bpy.data.objects['headlight2']
        light3 = bpy.data.objects['headlight3']
        light4 = bpy.data.objects['headlight4']

        if light1.energy==0.0:
            light1.energy = 0.8
        else:
            light1.energy = 0.0

        if light2.energy==0.0:
            light2.energy = 0.8
        else:
            light2.energy = 0.0

        if light3.energy==0.0:
            light3.energy = 0.8
        else:
            light3.energy = 0.0

        if light4.energy==0.0:
            light4.energy = 0.8
        else:
            light4.energy = 0.0

        return {'FINISHED'}

    def register():
        bpy.utils.register_class(LightsOperator)


    def unregister():
        bpy.utils.unregister_class(LightsOperator)

if __name__ == "__main__":
 register()

 # test call
 bpy.ops.object.lights_operator()

Tags: 脚本dataifobjectsdefcontextelseclass
1条回答
网友
1楼 · 发布于 2024-09-29 23:28:42

第一个问题是缩进(不确定这是否随着编辑而改变)-register和unregister是缩进的,这使它们成为类的一部分,而不是它们,取消缩进以使它们成为模块函数。这将使对register()的调用起作用,以便您的类可以作为bpy.ops.object.lights_operator()使用

主要的问题是能量不是物体的属性,当物体是光的时候,你会在数据下找到能量属性。在

if light1.data.energy==0.0:
    light1.data.energy = 0.8
else:
    light1.data.energy = 0.0

你可以做一些其他的改进-

在poll函数中,您可以更具体一些。不要只选择某个东西,而是检查它是否接近你想要的。在

^{pr2}$

不必为每个对象重新键入相同的代码,您可以使用循环和测试对每个对象使用相同的代码。这会给你留下一个简短的剧本-

import bpy

class LightsOperator(bpy.types.Operator):
    bl_idname = "object.lights_operator"
    bl_label = "Headlight Operator"

    @classmethod
    def poll(cls, context):
        return context.active_object.type == 'LAMP'

    def execute(self, context):
        for object in bpy.data.objects:
            # object.name[:9] will give us the first 9 characters of the name
            if object.type == 'LAMP' and object.name[:9] == 'headlight':
                if object.data.energy == 0.0:
                    object.data.energy = 0.8
                else:
                    object.data.energy = 0.0
        return {'FINISHED'}

def register():
    bpy.utils.register_class(LightsOperator)


def unregister():
    bpy.utils.unregister_class(LightsOperator)

if __name__ == "__main__":
    register()

# test call
bpy.ops.object.lights_operator()

相关问题 更多 >

    热门问题