3
$\begingroup$

In blender's collections, unique naming is beautifully handled by adding "00n" to supposed to be duplicate items. Since it is used everywhere in blender, is this a blender utility module that I can also use for my add-on? If so, can you give me an example or point me to the documentation of this module?

$\endgroup$

2 Answers 2

2
$\begingroup$

AFAIK there isn't a python utility to do this, it wouldn't be too difficult to emulate it

import bpy

import re
def strip_trailing_number(s):
    m = re.search(r'\.(\d{3})$', s)
    return s[0:-4] if m else s

def unique_name(collection, base_name):
    base_name = strip_trailing_number(base_name)
    count = 1
    name = base_name

    while collection.get(name):
        name = "%s.%03d" % (base_name, count)
        count += 1      
    return name

# check

print(unique_name(bpy.data.objects, "Cube"))
print(unique_name(bpy.data.objects, "Cube.004"))
$\endgroup$
1
  • $\begingroup$ I guess there's no choice but an own implementation. Thank you for the example code. $\endgroup$
    – user2100
    Commented Dec 6, 2015 at 8:35
1
$\begingroup$

The automatic renaming is done whether you like it or not, even with objects created by an add-on. It's not a special module or accessible via a function call.

If an object is created with a name that exists already, then the new object gets that name, and the object which formerly had that name is renamed to the next free name. The part that figures out the next free name is internal and automatic.

$\endgroup$
2
  • $\begingroup$ So only created objects? But what about for properties? $\endgroup$
    – user2100
    Commented Dec 6, 2015 at 8:17
  • $\begingroup$ ID properties (properties per object) don't auto rename, they are similar to a Dict key, so you must test if it exists first, then increment the desired name using some scheme of your own devising. Please ask a new separate question, or search this site, for information about bpy.props and ID properties. $\endgroup$
    – zeffii
    Commented Dec 6, 2015 at 9:48

You must log in to answer this question.