Files
BABA_YAGA/Assets/Editor/HierarchyEnhancer.cs

81 lines
3.0 KiB
C#
Raw Normal View History

2026-03-26 20:27:19 +07:00
// ===============================================================================
// HierarchyEnhancer - Quick Toggle for GameObjects
//
// Creator: Scove
// Last Updated: 2024-05-08
// Version: 2.0
//
// Purpose:
// Adds a handy toggle checkbox to the right side of every item in the Hierarchy.
// This allows you to enable or disable GameObjects instantly without selecting them.
//
// Key Features:
// 1. One-click activation/deactivation directly in Hierarchy.
// 2. Full Undo/Redo support integrated with Unity's system.
// 3. Optimized UI placement to avoid overlapping with object names.
// 4. Visual clarity: Helps quickly identify inactive objects in a complex tree.
//
// How to Use:
// 1. Place this script in an 'Editor' folder.
// 2. Look at your Hierarchy window; a small checkbox will appear on the far right.
// 3. Click the checkbox to toggle the Active/Inactive state of any GameObject.
// ===============================================================================
using UnityEditor;
using UnityEngine;
namespace Editor
{
[InitializeOnLoad]
public class HierarchyEnhancer
{
// Define the width of the toggle area
private const float TOGGLE_WIDTH = 16f;
static HierarchyEnhancer()
{
// Subscribe to the hierarchy item GUI event
EditorApplication.hierarchyWindowItemOnGUI += OnHierarchyItemGUI;
}
private static void OnHierarchyItemGUI(int instanceID, Rect selectionRect)
{
// Get the GameObject associated with this instance ID
GameObject obj = EditorUtility.EntityIdToObject(instanceID) as GameObject;
if (obj == null) return;
// Calculate the position for the Toggle (Aligned to the far right)
// selectionRect.xMax gives us the right boundary of the Hierarchy row
Rect toggleRect = new Rect(selectionRect);
toggleRect.x = selectionRect.xMax - TOGGLE_WIDTH;
toggleRect.width = TOGGLE_WIDTH;
// Check current active state
bool isActive = obj.activeSelf;
// Handle UI and changes
EditorGUI.BeginChangeCheck();
// Set the color based on active state (Optional polish)
Color originalColor = GUI.color;
if (!isActive) GUI.color = new Color(1f, 1f, 1f, 0.5f); // Dim the toggle if inactive
bool newActive = EditorGUI.Toggle(toggleRect, isActive);
GUI.color = originalColor; // Restore original color for other elements
if (EditorGUI.EndChangeCheck())
{
// Record undo before applying the change
Undo.RecordObject(obj, "Toggle GameObject Active State");
obj.SetActive(newActive);
// If it's a Prefab, mark the scene as dirty to ensure it saves
if (!Application.isPlaying)
{
EditorUtility.SetDirty(obj);
}
}
}
}
}