Function resolveName()

When you call this function, it gives you back a unique name in the Maya scene. Very useful when creating objects programmatically and you want to keep unique names in your scene (Essential when dealing with maya scripts).

If the string passed as parameter is not assigned yet, then the function returns the string itself, else it will return the string plus “_#”.

Python code:


def resolveName(n):
	name = n
	if cmds.objExists(n):
		i = 1
		while cmds.objExists(str(n) + "_" + str(i)):
			i+=1
		name = str(n) + "_" + str(i)
		print "Warning: Object named " + n + " already exists. Used " + name + " instead."
	return name

MEL code:

proc string resolveName(string $n){
	string $name = $n;
	if (`objExists $n`){
		int $i = 1;
		while (`objExists ($n + "_" + string($i))`){
			$i+=1;
		}
		$name = $n + "_" + string($i);
		print ("Warning: Object named " + $n + " already exists. Used " + $name + " instead.");
	}
	return $name;
}

Examples:

Suppose you want to create a series of objects using the same name. By calling the function before the name you don’t have to worry about naming conflicts:


import maya.cmds as cmds

num_spheres = 10
sphere_list = list()

for i in range(numspheres):
     new_sphere = cmds.sphere(n=resolveName("mySphere"))
     sphere_list.append(new_sphere)

This will create the spheres mySphere, mySphere_1, mySphere_2 and so on.
If you recall the function again, the numbering will start from the first available name.