You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Maya脚本开发:如何将选中对象的属性值填入textField?

Fixing the Maya Attribute Path Error in Your Script

Hey there! No worries at all about your wording—we’ve all been there as new script developers, especially when juggling a new language (both coding and human 😉). Let’s break down what’s going on and fix this issue.

What’s Causing the Error?

The TypeError: Object [u'pCube1'].translateX is invalid message tells us exactly the problem: when you use %s with your selected variable, you’re passing a list instead of a single object string.

Maya’s cmds.ls(selection=True) (which I assume you’re using to get the selected cube) returns a list of selected objects—even if only one cube is selected, it comes back as [u'pCube1'], not just 'pCube1'. When you plug that list into your format string, it creates an invalid attribute path: [u'pCube1'].translateX, which Maya can’t parse.

The Fix

You just need to extract the single object string from the selected list. Here’s how to do it properly, with error handling for when no object is selected:

# First, get the list of selected objects
selected_objects = cmds.ls(selection=True)

# Check if any objects are selected to avoid index errors
if selected_objects:
    # Grab the first (and only, in your case) selected object
    selected = selected_objects[0]
    
    # Now create your textField with the correct attribute path
    transX_value = cmds.textField(w=100, h=22, tx=cmds.getAttr("%s.translateX" % selected))
    # Repeat this pattern for transY, transZ, rotX, etc.
else:
    # Warn the user if nothing is selected
    cmds.warning("Please select an object first!")

Bonus: More Readable Formatting (Python 3/Maya 2022+)

If you’re using Maya 2022 or later (which supports Python 3), f-strings are a cleaner way to format your attribute paths:

if selected_objects:
    selected = selected_objects[0]
    transX_value = cmds.textField(w=100, h=22, tx=cmds.getAttr(f"{selected}.translateX"))

Quick Note for Multiple Objects

If you ever want to handle multiple selected objects later, you’d loop through the selected_objects list instead of grabbing just the first element. For now, though, this fix will get your single-object case working perfectly.

内容的提问来源于stack exchange,提问作者Charlotte Crouzet

火山引擎 最新活动