Skip to content
TheChatArchiveThe Chat Archive
o3-2025-04-16· OpenAIHugging Face LMArena Human Preference 140K

create script maya python texture transfer script

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with grok-3-preview-02-24’s answer.
  1. User

    create script maya python texture transfer script

  2. Assistant

    Hey there! 👋
    Sure—I can definitely help you whip up a Python script for Maya that transfers textures / shading networks from one object to another. 🖌️

    Before I jump into code, could you give me a bit more context so I hit the mark?

    1. What exactly do you want to “transfer”?
      • Just the file-texture nodes?
      • The whole shading network (file, place2d, bump, aiStandardSurface, etc.)?
      • Per-face assignments (multiple materials on the same mesh) or a single material per object?

    2. Is the target mesh already UV-mapped identically, or do you need UV transfer too?

    3. How do you want to specify the source/target?
      • Manually select them in the viewport and run the script?
      • Hard-coded names in the script?
      • Pick from a UI list?

    4. Maya version / renderer (Arnold, Redshift, VRay, etc.)?
      – Some nodes and attributes differ per renderer.

    5. Batch or interactive? Should it pop a dialog or just run quietly in the Script Editor?

    Give me those details and I’ll tailor a clean, commented script you can drop straight into Maya’s Script Editor or shelf. 😊

  3. User

    Error: invalid syntax

    File "", line 22

    cmds.error(f"Source object '{source_obj}' does not exist.")

    ^

    SyntaxError: invalid syntax

  4. Assistant

    That “invalid syntax” is Maya telling us it’s still running Python 2.7 (anything prior to Maya 2022).
    Python 2 can’t understand the new-school f-strings ( f"…{var}…" ) that showed up in Python 3.6, so every one of those has to be rewritten with .format() or string concatenation.

    Below is a compact, Maya-2.7-compatible script that:

    • Lets you pick a source object and one or more target objects.
    • Copies the exact same shading-network / texture assignments onto the targets.
    • Works whether the material is on the whole mesh or on individual faces.
    • Has an optional flag (duplicate=True) if you’d rather DUPLICATE the shading network instead of sharing it.

    Just paste the whole thing into Maya’s Script Editor (Python tab) or save it as a shelf button.

    # ============================================================
    # Texture / Material Transfer  (Python 2.7 / Maya ≤ 2020)
    # ------------------------------------------------------------
    # Select SOURCE first, then one or more TARGETS, and run.
    # If you want each target to get its own copy of the shading
    # network, set duplicateNetworks=True in transfer_selected().
    # ============================================================
    
    import maya.cmds as cmds
    
    # ------------------------------------------------------------
    # Helper :  return all shadingEngines connected to a transform
    # ------------------------------------------------------------
    def get_sg_nodes(dag):
        """Return a list of shadingEngine nodes connected to dag."""
        return cmds.listConnections(dag, type='shadingEngine') or []
    
    # ------------------------------------------------------------
    # Helper :  return just the faces on SRC that belong to SG
    # ------------------------------------------------------------
    def faces_on_object(sg, src):
        """Return the component list (faces) on src that live in sg."""
        members = cmds.sets(sg, q=True) or []
        return [m for m in members if m.startswith(src + '.f[')]   # only faces
    
    # ------------------------------------------------------------
    # Transfer core
    # ------------------------------------------------------------
    def transfer_material(source, target, duplicateNetworks=False):
        """
        Copy (or share) the materials from source -> target.
        If duplicateNetworks==True each SG (and its upstream
        network) is duplicated before assignment.
        """
        if not cmds.objExists(source):
            cmds.error("Source object '{0}' does not exist.".format(source))
        if not cmds.objExists(target):
            cmds.error("Target object '{0}' does not exist.".format(target))
    
        sg_nodes = get_sg_nodes(source)
        if not sg_nodes:
            cmds.warning("No shadingEngine attached to {0}".format(source))
            return
    
        for sg in sg_nodes:
            # What faces on SOURCE belong to this SG?
            src_faces = faces_on_object(sg, source)
            if not src_faces:
                continue
    
            # Build a parallel face list on the TARGET mesh
            tgt_faces = []
            for face in src_faces:
                # face looks like  |  pCube1.f[15]
                face_suffix = face.split(source, 1)[-1]   # e.g. ".f[15]"
                mapped_face = target + face_suffix
                if cmds.objExists(mapped_face):
                    tgt_faces.append(mapped_face)
    
            if not tgt_faces:
                # Whole-mesh assignment or vertex/edge components
                tgt_faces = [target]
    
            # Possibly duplicate the network ❓
            sg_to_use = sg
            if duplicateNetworks:
                dup = cmds.duplicate(sg, upstream=True, un=True)   # un=True == 'upstreamNodes'
                sg_to_use = dup[0]                                 # duplicate() returns a list
    
            # Finally assign
            cmds.sets(tgt_faces, e=True, forceElement=sg_to_use)
    
        print("✔  Transfer done :  {0}  ➜  {1}".format(source, target))
    
    # ------------------------------------------------------------
    # Convenience wrapper : use current selection
    # ------------------------------------------------------------
    def transfer_selected(duplicateNetworks=False):
        sel = cmds.ls(sl=True, long=True) or []
        if len(sel) < 2:
            cmds.error("Select SOURCE first, then TARGET object(s), then run.")
        src = sel[0]
        tgts = sel[1:]
        for t in tgts:
            transfer_material(src, t, duplicateNetworks)
    
    # ------------------------------------------------------------
    # Run it!  (Change duplicateNetworks to True if desired)
    # ------------------------------------------------------------
    if __name__ == "__main__":
        transfer_selected(duplicateNetworks=False)
    

    How to use

    1. In the viewport or Outliner, select the SOURCE mesh first, then any number of TARGET meshes.
    2. Execute the script (Python tab).
    3. Watch the Script Editor for the ✔ confirmation.

    Need each target to have its own independent material?
    Just edit the very last line:

    transfer_selected(duplicateNetworks=True)
    

    That toggles the network duplication.

    Feel free to shout if you need UI buttons, per-shader filtering, UV transfer, or anything else! 🎨

  5. User

    skin transfer script maya python

  6. Assistant

    Here’s a compact, “drop-in” Python-2.7 script for Maya ≤ 2020 that transfers skin weights from one mesh to any number of other meshes.
    (If you’re on Maya 2022+ with Python 3 you can still use it – Python 3 syntax is a superset of Python 2 here.)

    📝 What it does
    • You select the SOURCE skinned mesh first, then one or more TARGET meshes and run the script.
    • If a target already has a skinCluster it re-uses it; if not, it auto-binds the same influences as the source with your preferred bind settings.
    • It then calls copySkinWeights with practical defaults (closestPoint surface association, oneToOne then closestJoint influence association).
    • Works on poly meshes or nurbs surfaces.
    • Minimal UI – just run it from Script Editor or put it on a shelf.

    # ============================================================
    #  Skin-Weight Transfer  (Python 2.7 / Maya ≤ 2020)
    # ------------------------------------------------------------
    # 1. Select SOURCE skinned mesh, then TARGET mesh(es).
    # 2. Run the script.
    # ------------------------------------------------------------
    #  Options you might want to tweak are at the very top:
    #     SURFACE_ASSOC, INFLUENCE_ASSOC, BIND_IF_MISSING
    # ============================================================
    
    import maya.cmds as cmds
    
    # ----------------------------------------------------------------
    #  USER OPTIONS  (adjust to taste)
    # ----------------------------------------------------------------
    SURFACE_ASSOC    = 'closestPoint'         # 'closestPoint', 'rayCast', 'closestComponent'
    INFLUENCE_ASSOC  = ['oneToOne', 'closestJoint', 'label']
    BIND_IF_MISSING  = True                   # auto-bind targets that aren’t skinned
    
    # ----------------------------------------------------------------
    #  INTERNAL HELPERS
    # ----------------------------------------------------------------
    def find_skincluster(dag):
        """Return the first skinCluster upstream of dag (or None)."""
        hist = cmds.listHistory(dag, pdo=True) or []
        skins = cmds.ls(hist, type='skinCluster')
        return skins[0] if skins else None
    
    def bind_mesh(mesh, joints):
        """Create a new skinCluster on mesh with given joints (keeps options simple)."""
        sc = cmds.skinCluster(joints, mesh,
                              toSelectedBones=True,
                              bindMethod=0,     # classic linear
                              skinMethod=0,     # weight influence
                              normalizeWeights=1,
                              obeyMaxInfluences=False)[0]
        return sc
    
    def transfer_skin_weights(src_mesh, tgt_mesh,
                              surface_assoc=SURFACE_ASSOC,
                              influence_assoc=INFLUENCE_ASSOC,
                              bind_if_missing=BIND_IF_MISSING):
        """Core routine: copy weights from src_mesh ➞ tgt_mesh."""
        # ----------------- source checks -----------------
        src_skin = find_skincluster(src_mesh)
        if not src_skin:
            cmds.error("Source object '{0}' is not skinned.".format(src_mesh))
        src_jnts = cmds.skinCluster(src_skin, q=True, inf=True)
    
        # ----------------- target skinCluster ------------
        tgt_skin = find_skincluster(tgt_mesh)
        if not tgt_skin:
            if not bind_if_missing:
                cmds.warning("Target '{0}' is not skinned – skipped.".format(tgt_mesh))
                return
            tgt_skin = bind_mesh(tgt_mesh, src_jnts)
    
        # --------------- copySkinWeights -----------------
        cmds.copySkinWeights(ss=src_skin,
                             ds=tgt_skin,
                             noMirror=True,
                             surfaceAssociation=surface_assoc,
                             influenceAssociation=influence_assoc)
        print("✔  Skin weights copied  {0} ➜ {1}".format(src_mesh, tgt_mesh))
    
    # ----------------------------------------------------------------
    #  SELECTION WRAPPER
    # ----------------------------------------------------------------
    def transfer_selected():
        sel = cmds.ls(sl=True, long=True) or []
        if len(sel) < 2:
            cmds.error("Select SOURCE mesh first, then TARGET(s), and run.")
        source = sel[0]
        targets = sel[1:]
        for t in targets:
            transfer_skin_weights(source, t)
    
    # ----------------------------------------------------------------
    #  SCRIPT ENTRY
    # ----------------------------------------------------------------
    if __name__ == "__main__":
        transfer_selected()
    

    🛠️ How to use

    1. Load the script in Maya’s Script Editor (Python tab) or save it as a shelf button.
    2. In the viewport / Outliner, select the SOURCE (skinned) mesh first, then any number of TARGET meshes.
    3. Execute. Done!

    Need something fancier?
    • Mirror weights left ↔ right after transfer
    • Support for pruning / max influences
    • Little UI window with check-boxes

    Just let me know and I’ll extend it. Happy rigging! 🎮

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.