| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- using UnityEngine;
- using UnityEditor;
- using UnityEditor.SceneManagement;
- [InitializeOnLoad]
- public class HierarchyToggleEditor
- {
- static HierarchyToggleEditor()
- {
- // 注册 Hierarchy 窗口的绘制回调
- EditorApplication.hierarchyWindowItemOnGUI += OnHierarchyWindowItemGUI;
- }
- private static void OnHierarchyWindowItemGUI(int instanceID, Rect selectionRect)
- {
- // 获取当前绘制的 GameObject
- GameObject obj = EditorUtility.InstanceIDToObject(instanceID) as GameObject;
- if (obj == null) return;
- // 设置绘制区域(Hierarchy 左侧)
- Rect toggleRect = new Rect(selectionRect);
- toggleRect.x = 28; // 放置在左侧,靠近树状结构图标后方
- toggleRect.width = 20; // 按钮宽度
- toggleRect.height = EditorGUIUtility.singleLineHeight;
- // 自定义按钮样式
- GUIStyle toggleButtonStyle = new GUIStyle(GUI.skin.button) { fontSize = 10 };
- // 绘制启用/禁用按钮
- bool isActive = obj.activeSelf;
- if (GUI.Button(toggleRect, isActive ? "✔" : "✘", toggleButtonStyle))
- {
- // 记录 Undo 操作
- Undo.RecordObject(obj, isActive ? "Disable GameObject" : "Enable GameObject");
- obj.SetActive(!isActive);
- MarkDirty(obj);
- Debug.Log($"{(isActive ? "Disabled" : "Enabled")} GameObject {obj.name}");
- }
- }
- // 标记对象为脏,确保修改保存
- private static void MarkDirty(GameObject obj)
- {
- EditorUtility.SetDirty(obj);
- // 如果在预制件编辑模式中,保存预制件
- if (PrefabStageUtility.GetCurrentPrefabStage() != null)
- {
- var prefabStage = PrefabStageUtility.GetCurrentPrefabStage();
- if (prefabStage.prefabContentsRoot == obj || obj.transform.IsChildOf(prefabStage.prefabContentsRoot.transform))
- {
- PrefabUtility.SavePrefabAsset(prefabStage.prefabContentsRoot);
- Debug.Log($"Saved prefab changes for {prefabStage.prefabContentsRoot.name}");
- }
- }
- }
- }
|