I am trying to create multiple joined groups using this answer to an already existing question.
I am reading some coordinates from a file, creating spheres at those coordinates, and assigning a material of a certain color depending on the index. I would like to join together the spheres that have the same color.
Below is a minimal reproducible code:
import bpy
import numpy as np
coords = np.loadtxt('coordinates.dat')
# 0 (A)
matBlue = bpy.data.materials.new(name="blue")
matBlue.diffuse_color = (0,0,1)
# 1 (B)
matRed = bpy.data.materials.new(name="red")
matRed.diffuse_color = (1,0,0)
materialColors = {0:matBlue, 1:matRed}
spheres = [[],[]]
count = 0
for coord in coordinates:
bpy.ops.mesh.primitive_uv_sphere_add(location=(coord[0],coord[1],coord[2]), size=0.5)
name = 'sphere' + str(count)
bpy.context.active_object.name = name
currentSphere = bpy.data.objects[name]
currentSphere.data.materials.append(materialColors[count%2])
spheres[count%2].append(currentSphere)
count += 1
# join spheres
scene = bpy.context.scene
for i in range(2):
ctx = bpy.context.copy()
ctx['selected_objects'] = spheres[i]
ctx['active_object'] = spheres[i][0]
ctx['selected_editable_bases'] = [scene.object_bases[ob.name] for ob in spheres[i]]
bpy.ops.object.join(ctx)
However, when I do this, I end up with red spheres joined, and the blue spheres are not joined. What am I doing wrong?
Note: In reality, I have 8 groups instead of 2. Hence the for loop at the end.