How to set default value for array attributes

We were asked some array questions recently, and I found that there isn’t a good sample in Maya devkit. This article will demonstrate how to initialize an array with MArrayDataBuilder.  

MPxNode::Compute isn’t a good choice to give your array a default value. The reasons are that the compute will be called after a plug is dirty, or it will be connected on demand. The proper way to give your array a default value is to use the MPxNode::postConstructor method. For example, I can create a default value for the weightListNode sample from the Maya devkit with following code:

void weightList::postConstructor(){    MStatus status = MStatus::kSuccess;    // Get the datablock outside the compute with MPxNode::forceCache    MDataBlock block = this->forceCache();    // The remaining part is the same as compute    unsigned i, j;    MObject thisNode = thisMObject();    MPlug wPlug(thisNode, aWeights);     // Write into aWeightList    for( i = 0; i < 3; i++) {        status = wPlug.selectAncestorLogicalIndex( i, aWeightsList );        MDataHandle wHandle = wPlug.constructHandle(block);        MArrayDataHandle arrayHandle(wHandle, &status);        //McheckErr(status, "arrayHandle construction failedn");        MArrayDataBuilder arrayBuilder = arrayHandle.builder(&status);                for( j = 0; j < i+2; j++) {            MDataHandle handle = arrayBuilder.addElement(j,&status);                    float val = (float)(1.0f*(i+j));             handle.set(val);        }        status = arrayHandle.set(arrayBuilder);                wPlug.setValue(wHandle);        wPlug.destructHandle(wHandle);    }}

This will be called after the node is created and will insert three elements into the weightList attribute. That’s it :) 


Comments

Leave a Reply

Discover more from Autodesk Developer Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading