Skip to content
Advertisement

Any way to set multiple keys and values at once in Maya using python?

I’m looking for a solution, that allows to set list of values

[0,1,2]

over given list of times

[0,1,2]

at once, without loop, like this:

for frame, value in zip([0,1,2], [0,1,2]):
    cmds.keyframe(node, e=True, vc=value, t=frame)

There are commands

cmds.setKeyframe()

and

cmds.keyframe()

that allow to set animation keys at a given time But non of them allow to set range of value over the range of time (frames).

The same value can be put on the time range, but that’s not the case.

mel.eval("setKeyframe -e -v %s -t 0 -t 1 -t 2 %s" % (value, node))

I tried to get attributes of the animation curve node, that stores keys inside, but got an empty output.

node = '...'
types = cmds.listAttr(node)

for t in types:
    if cmds.objExists(node+t):
        try:
            print t, cmds.getAttr(node+t)
        except:
            print 'failed with', t
            continue

...
keyTimeValue [()]
...

Advertisement

Answer

Latest approach does not work in 2019 Maya. For those who will stumble upon, here is the proper code.

def add_keys(plugName, times, values, changeCache=None):
    # Get the plug to be animated.
    sel = om.MSelectionList()
    sel.add(plugName)
    plug = om.MPlug()
    sel.getPlug(0, plug)
    # Create the animCurve.
    animfn = oma.MFnAnimCurve(plug)
    timeArray = om.MTimeArray()
    valueArray = om.MDoubleArray()

    for i in range(len(times)):
        timeArray.append(om.MTime(times[i], om.MTime.uiUnit()))
        valueArray.append(values[i])
    # Add the keys to the animCurve.
    animfn.addKeys(
        timeArray,
        valueArray,
        oma.MFnAnimCurve.kTangentGlobal,
        oma.MFnAnimCurve.kTangentGlobal,
        False,
        changeCache)
Advertisement