Search code examples
pythonoopblenderbpy

Object methods in Blender3D?


I'm about 30 minutes into Blender's python API and I've been reading the documentation. Maybe I didn't look hard enough, but from what I'm seeing, I can't just assign an object (like an ico_sphere) to a variable named Sphere and then just modify its properties with methods?

import bpy

bpy.ops.object.select_all(action="SELECT")
bpy.ops.object.delete()

Sphere = bpy.ops.mesh.primitive_ico_sphere_add(location=[0,0,0])

# Does something like this work?
Sphere.set_color('red')

I do a lot of matplotlib and I was wondering, if bpy has a similar interface that is object oriented like that?


Solution

  • In blender, an operator returns a status, which would usually be {'FINISHED'}.

    After running an add object operator, the new object can be found in bpy.context.object.

    bpy.ops.mesh.primitive_ico_sphere_add(location=[0,0,0])
    Sphere = bpy.context.object
    Sphere.location = (1,2,3)
    Sphere.active_material = bpy.data.materials.new('mymat')
    Sphere.active_material.diffuse_color = (1,0,0,1)
    

    Note that node based materials need some more work. There is a blender specific SE site where you will find some script examples, like this.