pythonmayamaya-api

How to trigger a callback on referencing a file into the scene


In maya, I want to run a certain callback after anytime a new file gets referenced. I want to do this in python.

According to the docs this should be possible: https://help.autodesk.com/view/MAYAUL/2018/ENU/?guid=__py_ref_class_open_maya_1_1_m_scene_message_html

But when I register callbacks for kAfterLoadReference or kAfterLoadReferenceAndRecordEdits, the function never gets triggered. I connected a debugger and set a breakpoint and the callback function never even gets entered. I've tried both the addCallback and addReferenceCallback functions.

kAfterImport works as expected. Am I missing something obvious here, or is something actually broken?

checked in Maya 2018, 2019, and 2020

#create a new file called cube.ma, has a cube in it
TEST_SCENE_NAME = 'cube.ma'

cmds.file(new=1, f=1)
cmds.polyCube()
cmds.file(rn=TEST_SCENE_NAME)
cmds.file(s=1, f=1, type='mayaAscii')
cmds.file(new=1, f=1)

#register callbacks
import maya.api.OpenMaya as om2

def onReferenceLoad(clientData=None):
    print '#'*20
    print 'This is a callback'
    print '#'*20

id1 = om2.MSceneMessage.addReferenceCallback(om2.MSceneMessage.kAfterLoadReferenceAndRecordEdits, onReferenceLoad)
id2 = om2.MSceneMessage.addCallback(om2.MSceneMessage.kAfterLoadReferenceAndRecordEdits, onReferenceLoad)

id3 = om2.MSceneMessage.addReferenceCallback(om2.MSceneMessage.kAfterLoadReference, onReferenceLoad)
id4 = om2.MSceneMessage.addCallback(om2.MSceneMessage.kAfterLoadReference, onReferenceLoad)

id5 = om2.MSceneMessage.addCallback(om2.MSceneMessage.kAfterImportReference, onReferenceLoad)
id6 = om2.MSceneMessage.addCallback(om2.MSceneMessage.kAfterImport, onReferenceLoad)

#would expect this to trigger the callback method 5 times, doesn't trigger at all
print 'Referencing the test file'
cmds.file(TEST_SCENE_NAME, r=1, type='mayaAscii')

#correctly triggers the one callback registered
print 'Importing the test file'
cmds.file(TEST_SCENE_NAME, i=1)

#unregister callbacks
om2.MSceneMessage.removeCallbacks([id1,id2,id3,id4,id5,id6])

Solution

  • I'm also getting nothing when creating or importing a reference with those callbacks, but this one should give you what your expect:

    om2.MSceneMessage.addCallback(om2.MSceneMessage.kAfterCreateReference, onReferenceLoad)

    It will trigger when a new reference is created or an when it is loaded from an unloaded state.