Reputation: 11
I want to create a script in Maya using Python and bind it on a hotkey. Every time I run the script I want to loop through 3 states, cube/ cylinder / plane. So for example first time I run the script it will create a cube, second time delete the cube and create a cylinder third time delete the cylinder and create a plane., fourth time delete the plane and create a cube etc... I want this to happen until the user decides what primitive he wants and end the loop. I tried using while loop but I failed miserably.
Ended up with this:
def createCube():
return "cube"
def createCylinder():
return "cylinder"
def createPlane():
return "plane"
def numbers_to_primitives(argument):
switcher = {
1: createCube,
2: createCylinder,
3: createPlane,
}
# Get the function from switcher dictionary
func = switcher.get(argument, lambda: "Invalid primitive")
# Execute the function
print func()
numbers_to_primitives(2)
This kinda seems to work. But I foresee issues when running the command over and over as I am creating more and more primitives instead of replacing the existing ones. Would also need to create a toggle button to cycle through these?
Upvotes: 0
Views: 235
Reputation: 1978
You have several questions problems to solve. First, you want to use the script in a hotkey what means it should produce a different result every time you call numbers_to_primitive() without any argument. So you first need to save and read the current state. You have several ways to do it. If you only need the state in the current maya session, you can use a global variable like this:
state = 0
def box():
print "Box"
def cyl():
print "Cylinder"
def sph():
print "Sphere"
def creator():
global state
print "current state", state
state = state + 1
if state > 2:
state = 0
creator()
This way the state variable cycles through values 0-2. Now you want to create geometry and replace it as soon as the function is called again. It works very similiar: Save the current object and delete it as soon as the function is called again like this:
import maya.cmds as cmds
state = 0
transformName = "" #again a global variable
def box():
print "Box"
global transformName #to use the global variable you have do use "global" keyword
transformName, shape = cmds.polyCube()
def cyl():
print "Cylinder"
global transformName
transformName, shape = cmds.polyCylinder()
def sph():
print "Sphere"
global transformName
transformName, shape = cmds.polySphere()
def creator():
global state
funcs = [box, cyl, sph]
print "current state", state
print "TransformName", transformName
if cmds.objExists(transformName):
cmds.delete(transformName)
funcs[state]()
state = state + 1
if state > 2:
state = 0
Now you can call the creator() function and every time it will delete the old object and create a new one.
Upvotes: 1