Files
aibis-dream/Assets/Editor/EditorKit.cs
T
2026-01-28 16:20:19 +08:00

103 lines
3.4 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using UnityEditor;
using UnityEngine;
namespace AibisDream.SystemEditor
{
public static class EditorKit
{
public static readonly GUIStyle BoldFont = new(EditorStyles.label)
{
fontStyle = FontStyle.Bold
};
public static int SortingLayerField(string label, int id)
{
// 先获取layer
var layers = GetSortingLayerNames();
// 将ID转为idx
var idx = TransSortingLayer2Idx(id);
var newIdx = EditorGUILayout.Popup(label, idx, layers);
return TransIdx2SortingLayer(newIdx);
}
/// <summary>
/// 使用 SerializedProperty 绘制 SortingLayer 下拉菜单(基于ID
/// </summary>
/// <param name="label">显示的标签</param>
/// <param name="property">存储排序层ID的 SerializedPropertyint 类型)</param>
public static void SortingLayerField(GUIContent label, SerializedProperty property)
{
if (property == null || property.propertyType != SerializedPropertyType.Integer)
{
EditorGUILayout.HelpBox("Property must be an integer type for sorting layer ID.", MessageType.Error);
return;
}
EditorGUI.BeginChangeCheck();
// 获取所有排序层名称
string[] sortingLayerNames = GetSortingLayerNames();
// 将当前ID转为索引
int currentId = property.intValue;
int currentIndex = TransSortingLayer2Idx(currentId);
// 显示下拉菜单
int newIndex = EditorGUILayout.Popup(label, currentIndex, sortingLayerNames);
// 如果选择了新的排序层,更新属性值为新的ID
if (EditorGUI.EndChangeCheck() || newIndex != currentIndex)
{
int newId = TransIdx2SortingLayer(newIndex);
property.intValue = newId;
}
}
private static string[] GetSortingLayerNames()
{
// 获取所有 Sorting Layer 名称
var layerCount = SortingLayer.layers.Length;
var sortingLayerNames = new string[layerCount];
for (var i = 0; i < layerCount; i++)
{
sortingLayerNames[i] = SortingLayer.layers[i].name;
}
return sortingLayerNames;
}
private static int TransSortingLayer2Idx(int id)
{
var layers = SortingLayer.layers;
for (var i = 0; i < layers.Length; i++)
{
if (layers[i].id == id) return i;
}
return 0;
}
private static int TransIdx2SortingLayer(int idx)
{
if (idx < 0 || idx >= SortingLayer.layers.Length)
{
return SortingLayer.layers[0].id;
}
return SortingLayer.layers[idx].id;
}
public static void RecordObjectAndChildren(GameObject parent, string actionName)
{
Transform[] transforms = parent.GetComponentsInChildren<Transform>(true);
Object[] objectsToUndo = new Object[transforms.Length];
for (int i = 0; i < transforms.Length; i++)
{
objectsToUndo[i] = transforms[i].gameObject;
}
Undo.RegisterCompleteObjectUndo(objectsToUndo, actionName);
}
}
}