Working with Maya’s python api – The enum attribute

Here is some information on creating a enum attribute in maya python api.

 

Let’s start on creating an enum attribute that will work like an optionMenu.

First we create our enum class:

eAttr = OpenMaya.MFnEnumAttribute()

Then we can add our attribute to the class:

testNode.optionMenu= eAttr.create('options', 'options', 0)

Next we can add some ‘fields’ to the attribute. This is where we add the options to our optionMenu:

eAttr.addField('option1', 0)
eAttr.addField('option2', 1)
eAttr.addField('option3', 2)
eAttr.addField('option4', 3)
eAttr.addField('option5', 4)

There,  now we have 5 options available to choose from. When queried, we will get an int in return.

Next let’s set up some options in the MFnEnumAttribute class:

eAttr.setKeyable(1)
eAttr.setStorable(1)

We want to be able to key the option we want, and we want to be able to have current option save to the file.

Last, we need to add our newly created attribute to the node we are working on:

testNode.addAttribute(testNode.optionMenu)

The whole code for this enum attribute:

eAttr = OpenMaya.MFnEnumAttribute()

testNode.optionMenu= eAttr.create('options', 'options', 0)
eAttr.addField('option1', 0)
eAttr.addField('option2', 1)
eAttr.addField('option3', 2)
eAttr.addField('option4', 3)
eAttr.addField('option5', 4)
eAttr.setKeyable(1)
eAttr.setStorable(1)
testNode.addAttribute(testNode.optionMenu)

 

Next, lets look at how to get at our optionMenu when we need to:

When we want to get at the data, we need to create a dataBlock:

optionMenu_value = dataBlock.inputValue(testNode.optionMenu)

The variable ‘optionMenu_value’ now contains the data we want. We can use it like this:

if optionMenu_value.asInt() == 0:
    runThisCode()
if optionMenu_value.asInt() == 1:
    runThisCode()
if optionMenu_value.asInt() == 2:
    runThisCode()

etc.

This is an easy way to add a little option box to our plugin.

Leave a Reply

Your email address will not be published. Required fields are marked *