revival/game/Assets/Scripts/Util/Events/GameEvent.cs

107 lines
2.8 KiB
C#
Raw Permalink Normal View History

2021-02-23 10:52:00 +01:00
using System;
using System.Collections;
using System.Collections.Generic;
2021-05-16 21:00:39 +02:00
using System.Runtime.CompilerServices;
using NaughtyAttributes.Test;
2021-02-23 10:52:00 +01:00
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace Ktyl.Util
{
[CreateAssetMenu(menuName = "ktyl/Events/Game Event")]
2021-05-10 22:27:55 +02:00
public partial class GameEvent : ScriptableObject
2021-02-23 10:52:00 +01:00
{
[SerializeField] private bool _logRaised;
protected readonly List<GameEventListener> _listeners = new List<GameEventListener>();
2021-05-16 21:00:39 +02:00
private readonly List<GameEventListener> _listenerBuffer = new List<GameEventListener>();
2021-02-23 10:52:00 +01:00
public virtual void Raise()
{
if (_logRaised)
{
Debug.Log($"raised {this}", this);
}
2021-05-16 21:00:39 +02:00
// populate a buffer of listeners, since the original list
// may be modified as a consequence of triggering the event
_listenerBuffer.Clear();
_listenerBuffer.AddRange(_listeners);
foreach (var listener in _listenerBuffer)
2021-02-23 10:52:00 +01:00
{
2021-05-16 21:00:39 +02:00
listener.OnEventRaised();
2021-02-23 10:52:00 +01:00
}
}
public void Register(GameEventListener listener)
{
if (_listeners.Contains(listener))
{
Debug.LogError($"{listener} already registered", this);
return;
}
_listeners.Add(listener);
}
public void Unregister(GameEventListener listener)
{
if (!_listeners.Contains(listener))
{
Debug.LogError($"{listener} not already registered");
return;
}
_listeners.Remove(listener);
}
}
#region Editor
#if UNITY_EDITOR
2021-05-10 22:27:55 +02:00
public partial class GameEvent
{
private int _EDITOR_pingIdx;
public void EDITOR_PingNextListener()
{
Debug.Log($"ping listener {_EDITOR_pingIdx+1}/{_listeners.Count}", this);
EditorGUIUtility.PingObject(_listeners[_EDITOR_pingIdx++]);
_EDITOR_pingIdx %= _listeners.Count;
}
}
2021-02-23 10:52:00 +01:00
[CustomEditor(typeof(GameEvent), true)]
public class GameEventEditor : Editor
{
private GameEvent _event;
private void OnEnable()
{
_event = target as GameEvent;
}
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
if (GUILayout.Button("Raise"))
{
_event.Raise();
}
2021-05-10 22:27:55 +02:00
if (Application.isPlaying && GUILayout.Button("Ping Listeners"))
{
_event.EDITOR_PingNextListener();
}
2021-02-23 10:52:00 +01:00
}
}
#endif
#endregion
}