混合器:Python脚本失败(创建简单运算符)
我在Blender中自学Python,并尝试使用脚本创建一个简单的操作符。脚本如下-其目的是在场景中选择四个(聚光灯)并改变它们的能量(基本上,打开和关闭灯光)。但是当我尝试运行脚本时,会收到一条“Python脚本失败”错误消息。有人能看出代码有什么问题吗混合器:Python脚本失败(创建简单运算符),python,python-3.x,blender,Python,Python 3.x,Blender,我在Blender中自学Python,并尝试使用脚本创建一个简单的操作符。脚本如下-其目的是在场景中选择四个(聚光灯)并改变它们的能量(基本上,打开和关闭灯光)。但是当我尝试运行脚本时,会收到一条“Python脚本失败”错误消息。有人能看出代码有什么问题吗 import bpy def main(context): for ob in context.scene.objects: print(ob) class LightsOperator(bpy.types.Op
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()
第一个问题是缩进(不确定这是否随着编辑而改变)-register和unregister缩进,这使它们成为类的一部分,而它们不应该是类的一部分,取消缩进使它们成为模块函数。这将使对register()的调用起作用,这样您的类就可以作为
bpy.ops.object.lights\u操作符()使用了。
主要问题是能量不是对象的属性,当对象是灯光时,您将在数据下找到能量属性
if light1.data.energy==0.0:
light1.data.energy = 0.8
else:
light1.data.energy = 0.0
你还可以做一些其他的改进-
在poll函数中,您可以更具体一些。不要只是选择某个东西,而是检查它是否接近您想要的东西
return context.active_object.type == 'LAMP'
您可以使用循环和测试为每个对象使用相同的代码,而不是为每个对象重新键入相同的代码。这可能会给您留下这个较短的脚本-
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()
这是实际的缩进吗?我也建议你,在上发布关于blender的问题,我建议你在blenders专业python之外学习python。。。blender python可能会使用一些被认为是非音速或违反直觉的东西。。。如果那真的是你的缩进,我会仔细看一看,因为罪犯乔兰我复制了一个新版本,里面有你精确的缩进,但它仍然不起作用。我相信新的投票功能已经修复了它!谢谢sambler!