0
$\begingroup$

I try to run the following logic:

import bpy

# Active object is the cube, i selected it manually.
cube=bpy.context.active_object

# Add a sphere.
bpy.ops.mesh.primitive_uv_sphere_add(radius=1, location=(0.5, 0, 0), rotation=(0, 0, 0), scale=(1, 1, 1))
sphere=bpy.data.objects[-1]

# Change the active object to be the cube.
bpy.context['active_object'] = cube

# Add a boolean modifier to the cube with the sphere.
bpy.ops.object.modifier_add(type='BOOLEAN')
bpy.context.object.modifiers["Boolean"].object = sphere

What is supposed to happen here is that I have some object in my scene, for example a cube. I select it manually with my mouse and then I run the script. what should happen is that a sphere will be added to the scene, the active object will change back to the cube that I saved and then a boolean modifier will be added to the cube with the spere.

This fails with the error:

Error: Python: Traceback (most recent call last):
  File "\Text", line 49, in <module>
TypeError: bpy_struct[key] = val: id properties not supported for this type

I think that the problem is my understanding of how the active object is represented. I would appreciate a solution to that problem and if possible, an additional explanation of what are the bpy.context and bpy.data are. Thanks.

$\endgroup$

1 Answer 1

2
$\begingroup$

Your calling way for the active object is not fine. This script will create only one Sphere if there would not be otherwise if you already have sphere it'll not create another one.

import bpy

cube = bpy.context.active_object
sphere = bpy.data.objects.get('Sphere')
if not sphere:
    bpy.ops.mesh.primitive_uv_sphere_add()
    sphere = bpy.data.objects['Sphere']
else:
    sphere = bpy.data.objects['Sphere']
bpy.ops.object.select_all(action='DESELECT')

bpy.context.view_layer.objects.active = cube

mod_bool = cube.modifiers.new('Boolean', 'BOOLEAN')
mod_bool.object = sphere
$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .