Say for example i have an object made up of 3 (or more) cubes, loose meshes. I wanted to use script to iterate each loose mesh (cube).

Is it possible to loop through each loose body and store them in an array, then do something with them in a for loop?

enter image description here

  • $\begingroup$ Your question is not quite clear. When do you want to iterate through the objects, before or after they are separated by bpy.ops.mesh.separate(type='LOOSE')? Or is the iterating part irrelevant and you only want to separate them? $\endgroup$ – Robert Gützkow Apr 4 '20 at 14:58
  • $\begingroup$ thx I edited a bit on the quesiton, though i am thinking operating through 'bpy.ops.mesh.separate(type='LOOSE')` and then if there's way get the name of the separated objects would do? $\endgroup$ – adrian li Apr 4 '20 at 15:14
  • 1
    $\begingroup$ Related blender.stackexchange.com/questions/75332/… Get loose parts without separating as objects. Could be another dupe. Btw there's no need to delete your answer if it is marked a dupe. It' s as much house-keeping as anything $\endgroup$ – batFINGER Apr 4 '20 at 17:52

Separating objects based on disconnected geometry ("loose parts") can be accomplished through the operator bpy.ops.mesh.separate(type="LOOSE"). This operator attempts to separate all selected objects by loose parts. After its execution all separated objects, will be selected. If an object is initially selected, that doesn't contain loose parts, it will also be selected after the operator is finished. Therefore, you can access bpy.context.view_layer.objects.selected and get the resulting objects.

Depending on what you intend to do with the objects, you may not want to store references to the objects in a list. If you e.g. modify the collection or view layer, these references may become invalid and accessing them could crash Blender. The safest way is to store the unique names of the objects and access them by name when needed. This is explained in the Gotcha chapter of the API docs.

TL;DR: Do not keep direct references to Blender data (of any kind) when modifying the container of that data, and/or when some undo/redo may happen (e.g. during modal operators execution…). Instead, use indices (or other data always stored by value in Python, like string keys…), that allow you to get access to the desired data.

import bpy

# Separate the selected objects by disconnected geometry

# Get the selected objects
separated_obj_names = [obj.name for obj in bpy.context.view_layer.objects.selected]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.