From ce4310a63f9d528dcd988b7673ab733e179879f0 Mon Sep 17 00:00:00 2001 From: Ramon Brullo Date: Tue, 5 Nov 2024 15:53:46 +0100 Subject: [PATCH] feat: add material appy logic --- Code/ApplyMaterialToAll.cs | 65 +++++++++++++++++++++++++++++++++ Code/ApplyMaterialToAll.cs.meta | 3 ++ 2 files changed, 68 insertions(+) create mode 100644 Code/ApplyMaterialToAll.cs create mode 100644 Code/ApplyMaterialToAll.cs.meta diff --git a/Code/ApplyMaterialToAll.cs b/Code/ApplyMaterialToAll.cs new file mode 100644 index 0000000..cec848a --- /dev/null +++ b/Code/ApplyMaterialToAll.cs @@ -0,0 +1,65 @@ +#nullable enable + +using System.Linq; +using UnityEditor; +using UnityEngine; + +namespace At.Ac.FhStp.ApplyMaterialAll +{ + [InitializeOnLoad] + public static class ApplyMaterialToAll + { + private static GameObject? TryAsSelectedGameObject(int instanceID) + { + return EditorUtility.InstanceIDToObject(instanceID) as GameObject; + } + + private static Material? TryGetDraggedMaterial() + { + return DragAndDrop.objectReferences?.SingleOrDefault() as Material; + } + + private static void OnHierarchyGUI(int instanceID, Rect selectionRect) + { + var currentEvent = Event.current; + + // Must hold alt + if (!currentEvent.alt) return; + + // Must only drag single material + if (TryGetDraggedMaterial() is not { } material) return; + + // Must target game object + if (TryAsSelectedGameObject(instanceID) is not { } gameObject) + return; + + // Handle drag updated for feedback + if (currentEvent.type == EventType.DragUpdated) + { + DragAndDrop.visualMode = DragAndDropVisualMode.Copy; + currentEvent.Use(); + return; + } + + // Must be drag + if (currentEvent.type != EventType.DragPerform) return; + + DragAndDrop.AcceptDrag(); + + Undo.RegisterFullObjectHierarchyUndo(gameObject, + "Apply material to all"); + var meshRenderers = + gameObject.GetComponentsInChildren(); + foreach (var meshRenderer in meshRenderers) + meshRenderer.material = material; + EditorUtility.SetDirty(gameObject); + + currentEvent.Use(); + } + + static ApplyMaterialToAll() + { + EditorApplication.hierarchyWindowItemOnGUI += OnHierarchyGUI; + } + } +} \ No newline at end of file diff --git a/Code/ApplyMaterialToAll.cs.meta b/Code/ApplyMaterialToAll.cs.meta new file mode 100644 index 0000000..14dc37a --- /dev/null +++ b/Code/ApplyMaterialToAll.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 7f7b0b5b7c5c410b97179554a54748ae +timeCreated: 1728979512 \ No newline at end of file