0
$\begingroup$

I have a collection of objects named 'test0', 'test2'...'test999'.

When copying these objects between different Blender scenes/windows sometimes the internal collection order gets messed up and bpy.data.objects[0].name yields 'test11' (only an example, not sure of the pattern) instead of 'test0'.

But visual order in the outliner stays the same. Am I missing an easy way to get the order of the collection in the outliner? The info seems to be there.

Sorting alphabetically doesn't work either and outputs 'test1', 'test10'... enter image description here

$\endgroup$

1 Answer 1

1
$\begingroup$

As far as I know, there is no reliable way to ensure the order in which objects are stored in bpy.data.objects. In my experience, saving / loading and using the undo system can mess up the order.

You should never, ever rely on accessing objects by index in bpy.data.objects, unless you have a very specific workflow and even then I think you should use a workaround like custom properties, etc.

Objects are uniquely defined by their name in bpy.data.objects, and that's the only built-in way you can uniquely identify them with the API. The container acts like a dictionary AND a list since objects can be accessed by name and by index but I wouldn't ever use the latter if I want a reliable system.

Objects are (by default) ordered alphabetically in the outliner, that's why they stay ordered when copy/pasting.

You can get the objects ordered alphabetically with :

objects = sorted(bpy.data.objects[:], key=lambda obj: obj.name)

$\endgroup$
4
  • $\begingroup$ Bummer. Tried obj.name with sorted(), but order is like this then 'test0', 'test1', 'test10'. Alphabetically in outliner is different. $\endgroup$ Nov 23, 2022 at 13:45
  • $\begingroup$ Could you add a screenshot of your outliner to your question ? $\endgroup$
    – Gorgious
    Nov 23, 2022 at 14:05
  • 2
    $\begingroup$ Objects are sorted using BLI_strcasecmp_natrual but I don't know if you can call it from Python. Also see outliner_tree.cc. $\endgroup$
    – scurest
    Nov 23, 2022 at 14:49
  • $\begingroup$ Interesting. Surely someone somewhere has translated it to python. :) $\endgroup$
    – Gorgious
    Nov 23, 2022 at 16:03

You must log in to answer this question.

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