March 2019: ewertb.soundlinker.com is getting relocated to ewertb.mayasound.com, please update your bookmarks.

Maya API How-To #29

Back · Previous · Next Maya

How do I determine the type of a MPlug in order to use the appropriate getValue() overload?

The MPlug itself doesn't have a type, but its attribute does. Use the MPlug::attribute() method to get the MObject for the attribute. You can then use MObject::hasFn() to determine its type (e.g. kNumericAttribute, kTypedAttribute, kUnitAttribute, kMessageAttribute, etc.). If it's a numeric attribute then you can use MFnNumericAttribute::unitType() to query its numeric type.

MObject attribute = plug.attribute();

if ( attribute.hasFn( MFn::kNumericAttribute ) )
{
    MFnNumericAttribute fnAttrib(attribute);

    switch(fnAttrib.unitType())
    {
        case MFnNumericData::kBoolean:
        {
            bool value;
            plug.getValue(value);
            break;
        }
        case MFnNumericData::kShort:
        {
            short value;
            plug.getValue(value);
            break;
        }
        case MFnNumericData::kLong:
        {
            int value;
            plug.getValue(value);
            break;
        }
        case MFnNumericData::kFloat:
        {
            float value;
            plug.getValue(value);
            break;
        }
        case MFnNumericData::kDouble:
        {
            double value;
            plug.getValue(value);
            break;
        }
        case MFnNumericData::k3Float:
        {
            MVector float3;
            plug.child(0).getValue(float3.x);
            plug.child(1).getValue(float3.y);
            plug.child(2).getValue(float3.z);
        }
    }
}

Similarly, there's MFnUnitAttribute::unitType() for unit attributes and MFnTypedAttribute::attrType() for typed attributes.

Remember to consider for the case where the MPlug derives its value from an incoming connection. If a plug is connected, it may be animated (and thus its value may change from frame to frame), or - in the case of a (kFloat) or (k3Float) attribute - it may be connected to a texture. A texture connection has no valid value outside of Maya's rendering context, so any queries via getValue() are going to be non-representative of the plug's actual behavior.

19 Feb 2005