Last active
March 21, 2024 16:27
-
-
Save tomrijnbeek/2c6570e4eea3274904c6 to your computer and use it in GitHub Desktop.
Unity SendMessage alternative
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.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 | |
} |
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
public interface IListener<T> | |
{ | |
void T Listen(T message); | |
} |
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; | |
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