jpits
jpits

Reputation: 41

Import single OBJ files into Maya, moving and rotating it with Python/MEL

Hi I have this code to import OBJ files into maya with Python

**

import maya.cmds as cmds

pathOfFiles = "/Path/to/the/files/folder/"
fileType = "obj"

files = cmds.getFileList(folder=pathOfFiles, filespec='*.%s' % fileType)
if len(files) == 0:
    cmds.warning("No files found")
else:
    for f in files:
        cmds.file(pathOfFiles + f, i=True)

**

It imports all the obj files which are into that folder.

However, what I need is:

  1. Import an individual OBJ file at once
  2. Move and rotate the imported file
  3. Apply a Material already created in Maya
  4. Render
  5. Delete the file 6 Repeat the process with the next file

Is it possible to do it with Python or MEL

Upvotes: 0

Views: 1790

Answers (1)

Mr K
Mr K

Reputation: 33

This looks like a fun challenge, so here's my attempt at answering it:

import maya.cmds as cmds
import glob

#1. Import an individual OBJ file at once
def importFile(i):
    cmds.file(i, i=True, groupReference=True, groupName="myobj")

#2. Move and rotate the imported file
def moveFile():
    cmds.select("myobj")
    # Add the X,Y,Z cordinates to change scale, translate and rotate below
    cmds.scale(1,1,1)
    cmds.move(0,0,0)
    cmds.rotate(0,90,0)

#3. Apply a Material already created in Maya
    def materialFile():
    cmds.select("myobj")
    myMaterial = "lambert2" + "SG" #replace lambert2 with your material
    cmds.sets(forceElement=myMaterial)

#4. Render
def renderFile(i):
    cmds.setAttr("defaultRenderGlobals.imageFilePrefix", i, type="string")
    cmds.render(batch=True)

#5. Delete the imported file
def deleteFile():
    cmds.select("myobj")
    cmds.delete()

# Add the path to your obj files. Make sure to leave the /*.obj at the end
myglob = glob.glob("/Users/OSX/Desktop/objs/*.obj") 

for i in myglob:
    importFile(i)
    moveFile()
    materialFile()
    renderFile(i)
    deleteFile()

Because you have a list of individual things you need the script to do I've divided up each requirement on your list into its own function. This should make the script more modular and hopefully easy to edit and reuse.

Python works much better for this kind of task because MEL doesn't have functions, instead it has procedures which act like functions but don't work as well from what I've experienced.

Upvotes: 1

Related Questions