制作一个可以在Maya Python中循环经过3个不同状态的脚本

问题描述

我想使用Python在Maya中创建脚本并将其绑定到热键上。每次运行脚本时,我都想遍历3个状态,即立方体/圆柱体/平面。因此,例如,第一次运行脚本将创建一个多维数据集,第二次删除该多维数据集并创建一个圆柱体,第三次删除该圆柱体并创建一个平面,第四次删除该平面并创建一个多维数据集,等等。直到用户决定他想要什么原语并结束循环为止。我尝试使用while循环,但失败了。

结束于此:

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)

这有点奏效。但是,随着我创建越来越多的原语而不是替换现有的原语,一遍又一遍地运行命令时,我可以预见到问题。还需要创建一个切换按钮来循环这些操作吗?

解决方法

您有几个问题需要解决。首先,您想在热键中使用脚本,这意味着每次您调用不带任何参数的numbers_to_primitive()时,脚本应产生不同的结果。因此,您首先需要保存并读取当前状态。您有几种方法可以做到这一点。如果仅在当前maya会话中需要状态,则可以使用如下所示的全局变量:

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()

这样,状态变量将在值0-2之间循环。现在,您要创建几何并在再次调用该函数后立即替换它。它的工作方式非常相似:再次调用该函数,请保存当前对象并将其删除:

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

现在您可以调用creator()函数,每次它都会删除旧对象并创建一个新对象。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...