Hi all, I’m working on a Networking Library for Unity, I need to implement callbacks, or “messages” as the Unity doc calls them, such as OnConnectedToServer(), OnPlayerConnected(), etc, but I don’t know how to go about doing it. I’ve used delegates and interfaces before, but I can’t figure out how they work to create these callbacks that are built into MonoBehaviour. If anyone can provide insight or further reading it would be much appreciated. Thanks!!
You can use the Reflection.
The straightforward example can look like following.
class ConnectionData
{
// Some hypothetical data to be passed to the event with paramater
}
class Manager
{
List<System.Object> _listeners = new List<object>();
public void AddListener( System.Object listener )
{
if ( listener != null )
_listeners.Add( listener );
}
public void SendConnectedToServerMessages( ConnectionData data )
{
// Search non-static methods both public and non-public
BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
// Parameters of the method to search for
Type[] paramTypes = { typeof( ConnectionData ) };
// Parameter value to be passed to the method
System.Object[] paramValues = { data };
foreach ( System.Object obj in _listeners )
{
// Search for the method with signature OnConnectedToServer( ConnectionData )
MethodInfo methodInfo = obj.GetType()
.GetMethod( "OnConnectedToServer", flags, null, paramTypes, null );
// Call the method with parameters
if ( methodInfo != null)
methodInfo.Invoke( obj, paramValues );
}
}
}
Manager
stores links to the objects that should accept the events in _listeners
list, and then upon calling the SendConnectedToServerMessages()
searches through all the listeners, and if they have appropriate method - calls them with given parameters (if the listener has no such a method - nothing will be done).
Of course it is just a sample, more optimization would be nice to have (like precaching the MethodInfo structures) but this is the point to start from.
Reflection (C# and Visual Basic) | Microsoft Learn - this is the starting page for the Reflection topics on MSDN