Reputation: 1
Selecting Maya objects through memory using classes
What is the problem with the below code:
import maya.cmds as cmds
class MakeObject:
def __init__(self):
self.grp = cmds.createNode('transform')
def make_cube(self):
self.cube = cmds.polyCube(n='cube')[0]
cmds.parent(self.cube, self.grp)
def selection(self):
cmds.select(self.cube)
x = MakeObject()
x.make_cube()
y = MakeObject()
y.make_cube()
x.selection()
Upvotes: 0
Views: 289
Reputation: 4783
Unlike pymel
, cmds
doesn't use a wrapper to work with nodes. Instead it uses strings which can be problematic since they don't update dynamically. For example, if you create a new node my_cube = cmds.polyCube(n='cube')[0]
then rename it, the my_cube
variable will still be pointing the object's older name.
This could also be a problem if there are multiple objects in the scene that share the same duplicate name. Maya usually auto-renames duplicate naming to avoid conflicts, but it's valid to have duplicate names in different hierarchies. In this case you would have to access it by using the node's long name. For example, an object named "cube"
that's parented under another object named "root"
would have a long name "|root|cube"
.
All this being said, yes, there is a problem with this code. It's making 2 cubes with the same name and re-parenting them to a different hierarchy. So there will be 2 nodes with the name "cube"
. When the select
command is called, it's literately calling cmds.select("cube")
, but since there's more than one "cube"
Maya has no idea how to interpret that and then throws an error.
What can be done is to capture the object's new long name by doing this after it parents: self.cube = cmds.ls(sl=True, long=True)[0]
Now it's able to select the first cube as expected.
Upvotes: 1