Skip to content

Instantly share code, notes, and snippets.

@BigRoy
Last active February 27, 2024 23:23
Show Gist options
  • Save BigRoy/39985d60a3f20e599508 to your computer and use it in GitHub Desktop.
Save BigRoy/39985d60a3f20e599508 to your computer and use it in GitHub Desktop.
import maya.OpenMaya as om
import maya.cmds as mc
import uuid
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(clientData):
"""Ensure ids on all non-referenced nodes"""
nodes = mc.ls(long=True)
nodes = [node for node in nodes if not mc.referenceQuery(node, isNodeReferenced=True)]
for node in nodes:
ensure_id(node)
if __name__ == '__main__':
# Delete previous run (testing only)
if 'id' in globals():
try:
om.MMessage.removeCallback(id)
except RuntimeError, e:
print e
id = om.MSceneMessage.addCallback(om.MSceneMessage.kBeforeSave, callback)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment