Stray_Tom

Combine duplicate materials in Blender

Dec 21st, 2022
1,061
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1. import bpy
  2.  
  3. # Create a dictionary to store the materials with the same base color
  4. materials_dict = {}
  5.  
  6. # Iterate over all materials in the scene
  7. for mat in bpy.data.materials:
  8. # Get the base color of the material
  9. base_color = mat.diffuse_color
  10.  
  11. # Convert the base color to a hex string
  12. base_color_hex = '#%02x%02x%02x' % (int(base_color[0]*255), int(base_color[1]*255), int(base_color[2]*255))
  13.  
  14. # Check if the hex string is already in the dictionary
  15. if base_color_hex in materials_dict:
  16. # If it is, add the material to the list of materials with the same base color
  17. materials_dict[base_color_hex].append(mat)
  18. else:
  19. # If it isn't, create a new entry in the dictionary with the hex string as the key and the material as the value
  20. materials_dict[base_color_hex] = [mat]
  21.  
  22. # Iterate over the materials in the dictionary
  23. for hex_string, materials in materials_dict.items():
  24. # If there is only one material with the base color, skip it
  25. if len(materials) == 1:
  26. continue
  27.  
  28. # Create a new material
  29. new_mat = bpy.data.materials.new(name="Combined Material")
  30. # Set the base color of the new material
  31. new_mat.diffuse_color = materials[0].diffuse_color
  32.  
  33. # Iterate over all objects in the scene
  34. for obj in bpy.context.scene.objects:
  35. # Iterate over all materials assigned to the object
  36. for mat in obj.data.materials:
  37. # If the material is in the list of materials with the same base color, assign the new material to the object
  38. if mat in materials:
  39. obj.data.materials[obj.data.materials.find(mat.name)] = new_mat
  40.  
  41. # Delete the original materials
  42. bpy.data.materials.remove(materials)
Advertisement
Add Comment
Please, Sign In to add comment