Nicest way of fetching om.MFnMesh object from cmds.ls?

922 views
Skip to first unread message

Fredrik Averpil

unread,
Nov 16, 2016, 6:33:29 AM11/16/16
to python_in...@googlegroups.com

I have this:

import maya.api.OpenMaya as om
import maya.cmds as cmds

for mesh in cmds.ls(type='mesh'):
    selectionList = om.MSelectionList()
    selectionList.add(mesh)
    dagPath = selectionList.getDagPath(0)
    fnMesh = om.MFnMesh(dagPath)  # got it!

Is this the simplest/nicest way to iterate over all meshes and get the MFnMesh object or how would you improve this?

I’m asking primarily for readability purposes.

Regards,
Fredrik

vincent zaraek

unread,
Nov 16, 2016, 2:40:01 PM11/16/16
to Python Programming for Autodesk Maya
Hi Fredrik ,if you are working on maya 2017 you could use iterators, it should be faster/simplest
it = om.MItDag(om.MItDag.kDepthFirst,om.MFn.kMesh)
while not it.isDone():
fnMesh = om.MFnMesh(it.item())
        #do your stuff
it.next()
As far as I know, the python api 2.0 it hasn't iterators until maya 2017, or you could use standart maya api:
from maya import OpenMaya as om

Fredrik Averpil

unread,
Nov 17, 2016, 2:28:56 AM11/17/16
to Python Programming for Autodesk Maya
Hi Vincent,

Thanks for that, although I'm looking for something which will also work in Maya 2015/2016. I might just stick with what I have. I guess I just feel it's a bit odd that I need to create a list of objects (with one object) from which I can extract the DAG path ... instead of just using the DAG path directly from the "cmds.ls(type='mesh', )" command.

--
You received this message because you are subscribed to the Google Groups "Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_m...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/python_inside_maya/0d51a540-0273-4b51-9ff8-68f04e327923%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Cesar Saez

unread,
Nov 17, 2016, 7:51:02 AM11/17/16
to python_in...@googlegroups.com
It's a trade off, but you can always hide those details in a utility module or something.

# utils.py
import maya.api.OpenMaya as om2


def asSelectionList(iterable):
    selectionList = om2.MSelectionList()
    for each in iterable:
        selectionList.add(each)
    return selectionList


def asDagPaths(iterable):
    selectionList = asSelectionList(iterable)
    for i in xrange(selectionList.length()):
        yield selectionList.getDagPath(i)


# foo.py -- usage code
import maya.api.OpenMaya as om2
import maya.cmds as cmds
import utils  # utility module


for meshPath in utils.asDagPaths(cmds.ls(type='mesh')):
    fnMesh = om2.MFnMesh(meshPath)  # got it!
Reply all
Reply to author
Forward
0 new messages