← Back to maya
Export and Import Display Layers in Maya Python
15 May 26 (1mo ago)
Just a casual script to port layers from one maya scene to another. Granted that both should have similar objects. Also I'm just using the import counterpart these days on new scenes. Just modifying the existing json file.
Export Display Layers
import os
import json
import maya.cmds as cmds
def export_display_layers_to_json(output_path=r"D:\maya_display_layers.json"):
"""
Exports all custom display layers and their members to a JSON file,
excluding the default layer.
"""
layers = cmds.ls(type="displayLayer")
layer_data = {}
for layer in layers:
# Skip the default layer
if layer == "defaultLayer":
continue
# Get members of the layer. Returns None if empty.
members = cmds.editDisplayLayerMembers(layer, query=True)
layer_data[layer] = members if members else []
# Ensure the directory exists
dir_name = os.path.dirname(output_path)
if not os.path.exists(dir_name):
try:
os.makedirs(dir_name)
except Exception as e:
cmds.error(f"Could not create directory {dir_name}: {e}")
return
# Write the dictionary to a JSON file
try:
with open(output_path, 'w', encoding='utf-8') as json_file:
json.dump(layer_data, json_file, indent=4, sort_keys=True)
cmds.confirmDialog(
title="Export Successful",
message=f"Display layers exported to:\n{output_path}",
button=["OK"]
)
print(f"// Success: Display layers exported to {output_path} //")
except Exception as e:
cmds.error(f"Failed to write JSON file: {e}")
# Run the script
export_display_layers_to_json()
Import Display Layers
import maya.cmds as cmds
import os
import json
def add_display_layers(input_path=r"D:\maya_display_layers.json"):
"""
Imports display layers and their members from a JSON file.
Recreates layers if they don't exist and reassigns objects,
overriding any existing layer assignments.
"""
# 1. Check if the file exists
if not os.path.exists(input_path):
cmds.error(f"JSON file not found at: {input_path}")
return
# 2. Read the JSON data
try:
with open(input_path, 'r', encoding='utf-8') as json_file:
layer_data = json.load(json_file)
except Exception as e:
cmds.error(f"Failed to read JSON file: {e}")
return
# 3. Process each layer and its members
for layer_name, members in layer_data.items():
# Skip default layer just in case it sneaked into the JSON
if layer_name == "defaultLayer":
continue
# Create the display layer if it doesn't exist
if not cmds.objExists(layer_name):
layer_name = cmds.createDisplayLayer(empty=True, name=layer_name)
print(f"// Created display layer: {layer_name} //")
if not members:
continue
# Filter members to only include objects that actually exist in the current scene
valid_members = [obj for obj in members if cmds.objExists(obj)]
missing_members = [obj for obj in members if not cmds.objExists(obj)]
if missing_members:
print(f"// Warning: Missing scene objects skipped for layer '{layer_name}': {missing_members} //")
# Assign valid objects to the layer
for obj in valid_members:
# Force assignment: editDisplayLayerMembers overrides existing layers automatically,
# but explicitly doing it ensures the JSON mapping strictly prevails.
try:
cmds.editDisplayLayerMembers(layer_name, obj, noRecurse=True)
except Exception as e:
print(f"// Warning: Could not assign '{obj}' to '{layer_name}': {e} //")
print(f"// Success: Display layers setup complete from {input_path} //")
add_display_layers()