Skip to content

Instantly share code, notes, and snippets.

@sjkillen
Last active August 30, 2023 21:00
Show Gist options
  • Save sjkillen/c1e025e93ca5de46d4928aece86784b3 to your computer and use it in GitHub Desktop.
Save sjkillen/c1e025e93ca5de46d4928aece86784b3 to your computer and use it in GitHub Desktop.
Blender Python sort UV maps
from bpy.types import Mesh
def sort_uv_layers(mesh: Mesh):
# UV layers use non-pythonic reference semantics, safest to always reference by their indices
assert len(mesh.uv_layers) <= 7, "There must be fewer than 8 UV maps to sort (one less than the Blender maximum of 8)"
initial_layers = [[i, layer.name] for i, layer in enumerate(mesh.uv_layers)]
initial_layers.sort(key=itemgetter(1))
for i, layer_name in tuple(initial_layers):
assert mesh.uv_layers[i].name == layer_name, mesh.uv_layers[i].name + " " + layer_name
mesh.uv_layers.active = mesh.uv_layers[i]
new_layer = mesh.uv_layers.new(name=f"new_{mesh.uv_layers[i].name}")
assert new_layer == mesh.uv_layers[-1]
mesh.uv_layers.active = mesh.uv_layers[0]
mesh.uv_layers.remove(mesh.uv_layers[i])
for pair in initial_layers:
if pair[0] > i:
pair[0] -= 1
for layer in mesh.uv_layers:
layer.name = layer.name.replace("new_", "")
mesh.uv_layers.active = mesh.uv_layers[0]
@sjkillen
Copy link
Author

Sort the UV Layers / Maps on a Mesh based on their names. Useful for exporters which rely on the order of UVMaps

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment