うにてぃブログ

主にUnityとC#に関する記事を書いていきます

【C#】グローバルにイベントを管理する

使い方

EventMonitorジェネリッククラスになっているので Event を継承したクラスを利用する

object でもいいが、使う場所によってわざわざキャストするのが面倒だったのでこのような形になった

private void Main()
{
    // イベント追加
    EventMonitor<TestEvent>.Add(Test);
    // イベント通知
    EventMonitor<TestEvent>.Broadcast(new TestEvent());
    // イベント削除
    EventMonitor<TestEvent>.Remove(Test);
    // イベント全削除
    EventMonitor<TestEvent>.Clear();
}
 
private void Test(TestEvent e)
{
    Debug.LogError("call");
}
 
public class TestEvent : Event { }

コード

using System;
 
public abstract class Event {}
 
public static class EventMonitor<T> where T : Event
{
    private class EventInstance { }
 
    private static EventInstance i;
    private static Action<T> _events;
 
    public static void Add(Action<T> @event)
    {
        i ??= new EventInstance();
        _events += @event;
    }
 
    public static void Remove(Action<T> @event)
    {
        _events -= @event;
        if (_events == null)
        {
            i = null;
        }
    }
 
    public static void Broadcast(T @event)
    {
        if (i == null)
            return;

        _events?.Invoke(@event);
    }
 
    public static void Clear()
    {
        _events = null;
        i = null;
    }
}