Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Unity SendMessage alternative
using UnityEngine;
using System.Linq;
using System.Collections;
public static class GameObjectExtensions
{
public static void SendMessageToListeners<T>(this GameObject obj, T message)
{
foreach (var c in obj.GetInterfaceComponents<IListener<T>>())
c.Listen(message);
}
public static void BroadcastMessageToListeners<T>(this GameObject obj, T message)
{
foreach (var c in obj.GetInterfaceComponentsInChildren<IListener<T>>())
c.Listen(message);
}
#region Helpers
// GetComponents in Unity by default doesn't work with interface because they aren't registered, so we'll do it ourselves.
public static I[] GetInterfaceComponents<I>(this GameObject obj) where I : class
{
return obj.GetComponents(typeof(I)).Select (c => c as I).ToArray();
}
public static I[] GetInterfaceComponentsInChildren<I>(this GameObject obj) where I : class
{
return obj.GetComponentsInChildren(typeof(I)).Select (c => c as I).ToArray();
}
#endregion
}
public interface IListener<T>
{
void T Listen(T message);
}
using UnityEngine;
public class MonoBehaviourBase : MonoBehaviour
{
void SendMessageToListeners<T>(T message)
{
this.gameObject.SendMessageToListeners(message);
}
void BroadcastMessageToListeners<T>(T message)
{
this.gameObject.BroadcastMessageToListeners(message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.