Skip to content

Instantly share code, notes, and snippets.

@BigRoy
Last active April 14, 2023 03:13
Show Gist options
  • Save BigRoy/0c27c5bd8578625602ec to your computer and use it in GitHub Desktop.
Save BigRoy/0c27c5bd8578625602ec to your computer and use it in GitHub Desktop.
import maya.OpenMaya as om
import maya.cmds as mc
import uuid
def get_name(node):
"""Get the long name from the MObject where appropriate"""
if node.hasFn(om.MFn.kDagNode):
return om.MFnDagNode(node).fullPathName()
else:
return om.MFnDependencyNode(node).name()
def ensure_id(node):
"""Add a uuid attribute on the given node with a unique value.
Skips nodes that already have the attribute, unless when used upon duplicating.
Maya temporarily assigns the prefix '__PrenotatoPerDuplicare_' so we use that
to lookup whether it's currently being duplicated.
"""
node_attr = '{0}.uuid'.format(node)
value = str(uuid.uuid4())
if mc.objExists(node_attr):
# When duplicating refresh the ID
short_name = node.rsplit('|', 1)[-1]
if short_name.startswith('__PrenotatoPerDuplicare_'):
mc.setAttr(node_attr, lock=False)
mc.setAttr(node_attr, value, type='string')
mc.setAttr(node_attr, lock=True)
return
mc.addAttr(node, ln='uuid', dt='string')
mc.setAttr(node_attr, value, type='string')
mc.setAttr(node_attr, lock=True)
def callback(node, clientData):
node_name = get_name(node)
ensure_id(node_name)
if __name__ == '__main__':
# Delete previous run (testing only)
if 'id' in globals():
try:
om.MMessage.removeCallback(id)
except RuntimeError, e:
print e
id = om.MDGMessage.addNodeAddedCallback(callback)
@mottosso
Copy link

@BigRoy Got this in a Google result for "maya node created callback". It even auto-completed it for me. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment