Where there are 3 or sometimes more grids of different objects one behind the other. The objects are regularly spaced around 20 units in each axis, tho their origins are not always at a regular point. I need to select an even amount of objects from each of the grids so that I can merge them into a single grid with all the types of objects.
I have these code from another question I made that creates 20x20x80 cells and merges the objects inside of them:
import bpy
# grid layout in space
cell_offset = (-10, -40, -10)
cell_size = (20, 80, 20)
# little helper to snap values to a grid
def snap(val, step):
return (val//step) * step
objects = bpy.data.collections["Collection"].objects # take from a collection
#objects = bpy.context.selected_objects # or take selected objects
cells = {}
for obj in objects:
# snap the object's location to the next lower cell corner
key = (
snap(obj.location.x - cell_offset[0], cell_size[0]),
snap(obj.location.y - cell_offset[1], cell_size[1]),
snap(obj.location.z - cell_offset[2], cell_size[2])
)
# group objects with the same cell
if key not in cells:
cells[key] = [obj]
else:
cells[key].append(obj)
# select all objects in one cell and join them
for value in cells.values():
bpy.ops.object.select_all(action='DESELECT')
if len(value) > 1: # joining makes sense
bpy.context.view_layer.objects.active = value[0]
for obj in value:
obj.select_set(True)
bpy.ops.object.join()
Is there a way to tell it to select 1 of the objects in each cell at random instead of merging them?
I assume the code would help but if it has to be done differently that's also fine.
from random import choice
at the top of your file then afterbpy.ops.object.select_all(action='DESELECT')
simply usechoice(value).select_set(True)
. Btwvalue
is not the best variable name in this case, I would set it toobjects
or sth like that $\endgroup$for objects in cells.values(): with bpy.context.temp_override(object=objects[0], selected_editable_objects = objects): bpy.ops.object.join()
see blender.stackexchange.com/questions/248274/… $\endgroup$