With this post I’m going back to a topic I touched on briefly a couple months ago – MPlugs. In this installment I’ll be covering how to create MPlugs on an existing node.
First we need a node to work with. So lets make a polygon sphere.
import maya.cmds as cmds
cmds.polySphere( name='plugTest' )
Now we’ll add a new plug of the type String. It’s important to note here that an MPlug can refer to a few different types of attributes. MPlugs are the thing that moves data between two nodes while the attribute is the type of data being moved. So whenever you make an MPlug you need to assign it a data type. Here is how that’s done for a String.
Creating the attribute requires choosing the correct attribute class. There are nine different attribute classes to choose. Some of which I’ll cover in later posts, but for now all we need is MFnTypedAttribute. When creating the attribute we specify which data type it will be using MFnData (kString for a String). And finally, MDGModifier is used to add the newly created attribute to the MObject.
import maya.OpenMaya as OpenMaya
def getMObject( obj_name ):
sel_list = OpenMaya.MSelectionList()
sel_list.add( obj_name )
obj = OpenMaya.MObject()
sel_list.getDependNode( 0, obj )
sphere_obj = getMObject( 'plugTest' )
mdg_mod = OpenMaya.MDGModifier()
typed_attr = OpenMaya.MFnTypedAttribute()
attr = typed_attr.create( 'testPlug', 'tp', OpenMaya.MFnData.kString )
mdg_mod.addAttribute( sphere_obj, attr )