Hey Everyone!
I’m working on a multiplayer game with a few of my friends, and we are in the middle of an overhaul on our architecture, including networking. We aren’t confident in what networking API we ultimately want to use, so for flexibility I’m trying to create abstract classes for all our networking needs that can have concrete versions implemented for each API (Unity internal, uLink, Photon, etc). The main allure here is that the rest of our code base won’t have to worry about the underlying networking implementation, and can just generically use the abstract class.
The issue I’m mainly facing is dealing with the varying object types each API uses. The example below clearly illustrates the problem.
Lets say I have an abstract class called “InitNetwork” and I want it to force concrete implementations to deal with a common network event, such as when a player connects:
public abstract class InitNetwork : MonoBehaviour {
public abstract void OnPlayerConnected(Object networkPlayer);
}
Now, every networking API has a different version of Unity’s NetworkPlayer object, so at the abstract class level I’ve used Object as the parameter. The plan is to pass the NetworkPlayer variant in in the concrete implementation and cast it. Now, this abstract version of the event won’t actually be called, so each concrete class has to also implement its “native” version of the event, like so:
public class UnityInitNetwork: InitNetwork{
List<NetworkPlayer> connectedPlayers; // initialized somewhere
void OnPlayerConnected(NetworkPlayer networkPlayer){
OnPlayerConnected(networkPlayer);
}
public override void OnPlayerConnected (Object networkPlayer){
connectedPlayers.Add(((NetworkPlayer) networkPlayer));
}
}
So, I’m catching the native event, and passing the NetworkPlayer parameter into the overridden OnPlayerConnected method.
Now, we run into the issue: UnityEngine.Object will not cast to UnityEngine.NetworkPlayer (Error: “Cannot convert type ‘UnityEngine.Object’ to type ‘UnityEngine.NetworkPlayer’”). This surprised me; I though you could cast an Object to pretty much anything as long as you knew the proper type.
Does anyone know how to overcome this casting issue, or perhaps know a better way to approach creating an abstract networking class?