prime31
11/25/2015 - 11:59 PM

ActionExtensions.cs

using UnityEngine;
using System.Collections;
using System;


namespace Prime31
{
	public static class ActionExtensions
	{
		/// <summary>
		/// null checks any delegates listening to an event to ensure they are still active. Note that anonymous method with no target (i.e. no member access) will not get fired
		/// </summary>
		private static void invoke( Delegate listener, object[] args )
		{
			// we only null check the target if the method isnt static
			if( !listener.Method.IsStatic && ( listener.Target == null || listener.Target.Equals( null ) ) )
				Debug.LogError( "an event listener is still subscribed to an event with the method " + listener.Method.Name + " even though it is null. Be sure to balance your event subscriptions." );
			else
				listener.Method.Invoke( listener.Target, args ); // ((Action<T>)t).Invoke( param );
		}
		
		
		/// <summary>
		/// safely fires an event
		/// </summary>
		public static void fire( this Action handler )
		{
			if( handler == null )
				return;
			
			var args = new object[] {};
			foreach( var listener in handler.GetInvocationList() )
				invoke( listener, args );
		}
	
	
		/// <summary>
		/// safely fires an event
		/// </summary>
		public static void fire<T>( this Action<T> handler, T param )
		{
			if( handler == null )
				return;
			
			var args = new object[] { param };
			foreach( var listener in handler.GetInvocationList() )
				invoke( listener, args );
		}
	
		
		/// <summary>
		/// safely fires an event
		/// </summary>
		public static void fire<T,U>( this Action<T,U> handler, T param1, U param2 )
		{
			if( handler == null )
				return;
			
			var args = new object[] { param1, param2 };
			foreach( var listener in handler.GetInvocationList() )
				invoke( listener, args );
		}
	
		
		/// <summary>
		/// safely fires an event
		/// </summary>
		public static void fire<T,U,V>( this Action<T,U,V> handler, T param1, U param2, V param3 )
		{
			if( handler == null )
				return;
			
			var args = new object[] { param1, param2, param3 };
			foreach( var listener in handler.GetInvocationList() )
				invoke( listener, args );
		}
	}
}