Files
zeling_v2/Assets/Scripts/Editor/EventChannelEditor.cs
2026-05-12 15:34:08 +08:00

93 lines
3.1 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 System;
using UnityEditor;
using UnityEngine;
using BaseGames.Core.Events;
namespace BaseGames.Editor
{
/// <summary>
/// 为 VoidEventChannelSO 提供 Inspector 内的"Raise测试触发"按钮。
/// 仅在 Play Mode 下可用,防止在编辑状态误触发副作用。
/// </summary>
[CustomEditor(typeof(VoidBaseEventChannelSO), true)]
public class VoidEventChannelSOEditor : UnityEditor.Editor
{
public override void OnInspectorGUI()
{
DrawDefaultInspector();
EditorGUILayout.Space(6);
EditorGUI.BeginDisabledGroup(!Application.isPlaying);
if (GUILayout.Button("▶ Raise测试触发", GUILayout.Height(28)))
{
var channel = (VoidBaseEventChannelSO)target;
channel.Raise();
Debug.Log($"[EventChannelEditor] Raised: {target.name}");
}
EditorGUI.EndDisabledGroup();
if (!Application.isPlaying)
{
EditorGUILayout.HelpBox("进入 Play Mode 后可点击 Raise 触发此事件。", MessageType.Info);
}
}
}
/// <summary>
/// 为所有 BaseEventChannelSO&lt;T&gt; 子类提供 Inspector 内的订阅者数量显示和说明标签。
/// 因泛型限制Raise 按钮由具体类型的派生 Editor 提供(见下方注册器)。
/// </summary>
[CustomEditor(typeof(ScriptableObject), true)]
public class GenericEventChannelSOEditor : UnityEditor.Editor
{
// 仅对 BaseEventChannelSO<T> 子类生效
private bool _isEventChannel;
private void OnEnable()
{
var t = target.GetType();
while (t != null && t != typeof(object))
{
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(BaseEventChannelSO<>))
{
_isEventChannel = true;
break;
}
t = t.BaseType;
}
}
public override void OnInspectorGUI()
{
if (!_isEventChannel)
{
DrawDefaultInspector();
return;
}
DrawDefaultInspector();
EditorGUILayout.Space(6);
EditorGUI.BeginDisabledGroup(true);
if (Application.isPlaying)
{
// 反射获取订阅者数量
var field = target.GetType().GetField("OnEventRaised",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
if (field != null)
{
var del = field.GetValue(target) as Delegate;
int count = del?.GetInvocationList().Length ?? 0;
EditorGUILayout.LabelField("当前订阅者数量", count.ToString());
}
}
EditorGUI.EndDisabledGroup();
if (!Application.isPlaying)
{
EditorGUILayout.HelpBox("进入 Play Mode 可查看实时订阅者数量。", MessageType.Info);
}
}
}
}