using System;
using UnityEditor;
using UnityEngine;
using BaseGames.Core.Events;
namespace BaseGames.Editor
{
///
/// 为 VoidEventChannelSO 提供 Inspector 内的"Raise(测试触发)"按钮。
/// 仅在 Play Mode 下可用,防止在编辑状态误触发副作用。
///
[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);
}
}
}
///
/// 为所有 BaseEventChannelSO<T> 子类提供 Inspector 内的订阅者数量显示和说明标签。
/// 因泛型限制,Raise 按钮由具体类型的派生 Editor 提供(见下方注册器)。
///
[CustomEditor(typeof(ScriptableObject), true)]
public class GenericEventChannelSOEditor : UnityEditor.Editor
{
// 仅对 BaseEventChannelSO 子类生效
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);
}
}
}
}