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$
5
  • $\begingroup$ Bummer. Tried obj.name with sorted(), but order is like this then 'test0', 'test1', 'test10'. Alphabetically in outliner is different. $\endgroup$ Commented Nov 23, 2022 at 13:45
  • $\begingroup$ Could you add a screenshot of your outliner to your question ? $\endgroup$ Commented 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$ Commented Nov 23, 2022 at 14:49
  • $\begingroup$ Interesting. Surely someone somewhere has translated it to python. :) $\endgroup$ Commented Nov 23, 2022 at 16:03
  • $\begingroup$ I used objs.sort(key=lambda x: x.name_full.lower()) to sort the objects like in the outliner :) It still doesn't sort test1 and test10 correctly unfortunately $\endgroup$ Commented Oct 11, 2024 at 18:33

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.