Created
November 25, 2015 23:59
-
-
Save prime31/8b9658e387f06ca2600f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment