2014-05-23 129 views
0

我在教自己在Blender中使用Python,並試圖使用腳本創建一個簡單的操作符。劇本在下面 - 它的目的是在場景中選擇四個(點)燈並改變它們的能量(基本上,打開和關閉燈光)。但是,當我嘗試運行該腳本時,出現「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() 
+1

這是實際的縮進嗎? – jonrsharpe

+0

我也推薦你在[這個專用的StackExchange站點](http://blender.stackexchange.com/)上發佈有關攪拌器的問題 –

+0

我會推薦學習python以外的攪拌器專門的python ... blender python很可能會使用一些被認爲是不合理的或者違反直覺的東西。 –

回答

0

第一個問題是壓痕(不知道這改變了與編輯) - 註冊和註銷的縮進,這使得他們,他們不應該是類的一部分,取消縮進,使它們模塊功能。這將使呼叫register()的工作,以便您的類將可用作爲bpy.ops.object.lights_operator()

主要問題是,能源不是一個對象的屬性,你會發現能源屬性下的數據時,對象是一盞燈。

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

一些其他方面的改進,你可以做 -

在該查詢功能,你可以更具體。不要只是選擇一些東西,而是檢查它接近你想要的。

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() 
+0

我確實相信新的調查功能已經修復了它!謝謝你的冒險家! – user3669644