ソースコード
using System;
using System.Collections.Generic;
namespace Kogane
{
<summary>
</summary>
public static class MessageBroker
{
private static Dictionary<Type, object> m_callbacksTable = new();
#if UNITY_EDITOR
<summary>
</summary>
[UnityEditor.InitializeOnEnterPlayMode]
private static void InitializeOnEnterPlayMode()
{
m_callbacksTable = new();
}
#endif
<summary>
</summary>
public static void Add<T>( Action<T> callback )
{
var type = typeof( T );
if ( !m_callbacksTable.ContainsKey( type ) )
{
m_callbacksTable[ type ] = new List<Action<T>>();
}
var callbacks = ( List<Action<T>> )m_callbacksTable[ type ];
callbacks.Add( callback );
}
<summary>
</summary>
public static void Remove<T>( Action<T> callback )
{
var type = typeof( T );
if ( !m_callbacksTable.ContainsKey( type ) ) return;
if ( m_callbacksTable[ type ] == null ) return;
var callbacks = ( List<Action<T>> )m_callbacksTable[ type ];
callbacks.Remove( callback );
}
<summary>
</summary>
public static void Send<T>( T data )
{
var type = typeof( T );
if ( !m_callbacksTable.TryGetValue( type, out var value ) ) return;
var callbacks = ( List<Action<T>> )value;
if ( callbacks is not { Count: > 0 } ) return;
foreach ( var callback in callbacks )
{
callback( data );
}
}
}
}