我在Blender中的Python脚本遇到严重问题

1 投票
1 回答
1026 浏览
提问于 2025-04-18 13:57

最近我开始用C++和OpenGL搭建一个3D游戏引擎,但我想用Python写个脚本,把场景中的一些物体导出到文件里。现在一切都进行得很顺利,除了我对Python API如何处理物体和不同类型物体的问题有些困惑。

代码:

for Lampa in Lamp.Get():          # In this case we are working with lamps
    Lampatipus=Lampa.getType()
    if Lampa.getParent()==Targy\  # Objects have parents in blender, but it shows error that lamps doesn't have functions like getParent()
    and Lampatipus=="Lamp":

        self.file.write(Lampa.getName())
        self.file.write("\00")

        # Lampa beallitasai

        Lampa_alap_tomb=array('f', [\
        Lampa.LocX, # Shows error message that lamps doesnt have position x...
        Lampa.LocY,
        Lampa.LocZ,
        Lampa.R,
        Lampa.G,
        Lampa.B,
        Lampa.getEnergy()/10.0,
        Lampa.color[0],
        Lampa.color[1],
        Lampa.color[2],
        Lampa.color[3]\
        ])
Lampa_alap_tomb.tofile(self.file)

# Another case:

for Lampa in Jelenet.objects:          # In this case we are working with objects
   Lampatipus=Lampa.getType()
   if Lampa.getParent()==Targy\  # no problem here

        self.file.write(Lampa.getName())
        self.file.write("\00")

        # Lampa beallitasai

        Lampa_alap_tomb=array('f', [\
        Lampa.LocX,
        Lampa.LocY,
        Lampa.LocZ,
        Lampa.R, # Shows error message that objects doesnt have R (red component of color of a light)
        Lampa.G,
        Lampa.B,
        Lampa.getEnergy()/10.0,
        Lampa.color[0],
        Lampa.color[1],
        Lampa.color[2],
        Lampa.color[3]\
        ])
        Lampa_alap_tomb.tofile(self.file)

代码结束!!

举个例子,如果我想遍历所有的灯光,并把它们的一些属性(比如名字、颜色、父对象等)写入文件,有些灯光的属性在Python中并不能被识别为不同对象使用的变量。如果我遍历所有对象,先获取对象的类型(实际上是灯光),但是控制台却显示错误信息,比如说“聚光灯半径”或其他属性不是“Blender对象”的属性。在前面的例子中,我提到Python没有意识到“Blender灯光”实际上是“Blender对象”,但我认为“Blender灯光”应该也继承自“Blender对象”的原始属性。因为在Blender中,不管对象是什么类型,它都有位置、旋转、缩放等等。到目前为止,正如你所知道的,每个灯光都有位置(就像其他对象一样),还有光的属性(光的颜色等)。但是如果我想获取一个Blender灯光的位置,它却不工作,因为它显示这种灯光不是一个对象,但在Blender中,灯光也有位置和其他正常对象一样的属性。我在Blender 2.49的Python API文档中也没有找到关于灯光位置的参考资料。

请帮帮我!谢谢!

附言:抱歉我的英语,我来自匈牙利,没有专业背景。我写的一些变量是匈牙利语,但我希望你能理解这个问题。谢谢!

1 个回答

1

你还在用2.49版本吗?那已经很旧了。如果你不使用2.49版本,那么2.49的API文档对你就没什么帮助了,因为从2.50开始,Python的用法就全变了。如果你用的是更新的版本,建议你查看当前的blender API文档,会对你更有帮助。

如果你在使用较新的blender版本,下面的内容应该会对你有用 -

import bpy

for obj in bpy.context.scene.objects:
    if obj.type == 'LAMP' and obj.parent == Targy:
        print(obj.name)
        print(obj.location.x)
        print(obj.data.color.r)
        print(obj.data.energy)

不要把obj.colorobj.data.color搞混了。obj.color是一个所有对象都可以用的属性,而灯光则使用obj.data.color来设置它的光色。

撰写回答