Skip to content

Instantly share code, notes, and snippets.

@tomrijnbeek
Last active March 21, 2024 16:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomrijnbeek/2c6570e4eea3274904c6 to your computer and use it in GitHub Desktop.
Save tomrijnbeek/2c6570e4eea3274904c6 to your computer and use it in GitHub Desktop.
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