Hi all! I’m writing notification system script. Please, help me improve it.
I will be glad to see comments and remarks. Sorry for my English:)
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public static class MyNotifications
{
public delegate void ComponentDelegate ( Component sender, ComponentEventArgs e );
private static Dictionary<string, ComponentDelegate> _events = new Dictionary<string, ComponentDelegate> ();
/// <summary>
/// Adds the observer.
/// </summary>
/// <param name='method'>
/// Method for call.
/// </param>
public static void AddObserver ( ComponentDelegate method )
{
if ( _events.ContainsKey ( method.Method.Name ) )
_events[ method.Method.Name ] += method;
else
_events.Add ( method.Method.Name, method );
}
/// <summary>
/// Posts the notification.
/// </summary>
/// <param name='sender'>
/// Sender.
/// </param>
/// <param name='name'>
/// Event name.
/// </param>
/// <param name='e'>
/// Parameters.
/// </param>
public static void PostNotification ( Component sender, string name, ComponentEventArgs e )
{
if ( _events.ContainsKey ( name ) )
{
ComponentDelegate curEvent = _events[ name ];
foreach ( ComponentDelegate del in curEvent.GetInvocationList () )
{
if ( del.Target.ToString () == "null" )
{
curEvent -= del;
}
}
if ( curEvent != null )
curEvent ( sender, e );
}
}
}
public class ComponentEventArgs : System.EventArgs
{
public object UserData;
new public static readonly ComponentEventArgs Empty = new ComponentEventArgs ();
}
Usability:
using UnityEngine;
using System.Collections;
public class TestA : MonoBehaviour
{
void Awake ()
{
MyNotifications.AddObserver ( OnSomething );
}
void OnSomething ( Component sender, ComponentEventArgs e )
{
print ( sender.gameObject.tag );
print ( e.UserData );
}
}
using UnityEngine;
using System.Collections;
public class TestB : MonoBehaviour
{
void Start ()
{
MyNotifications.PostNotification ( this, "OnSomething", new ComponentEventArgs { UserData = 2.3f } );
}
}