Networking in Unity

I considered taking part in the Global Game Jam, and realised Godot wasn’t going to be a good choice if I wanted to collaborate with anyone, so I re-imlpemented what I already had in Unity. Since I hadn’t gotten very far this was quite straightforward.

On the plus side, Unity is more mature, has lots more documentation and resources available, and fully supports Visual Studio, which has an awesome vim plugin. On the other hand, it’s proprietary and the only OS I can run it on is Windows.

Anyway, Unity also has built-in networking support, and if I want to play the game I’m making with anyone I know it’s going to have to work online.

Programming Time

I have never written networked game code before. Using a combination of this tutorial and the Unity networking manual, I was able to get to this point in a matter of hours. As a side-note, the client on the left is running on Linux, and it Just Worked™.

There’s only a couple of steps required to get basic object position synchronisation working. First, you have to make one of the clients act as a server, then register it with Unity’s Master Server, a sort of directory for servers.

String gameType = "meshist_network_tutorial_game";
Network.InitializeServer(32, 25000, !Network.HavePublicAddress());
MasterServer.RegisterHost(gameType, "My Lovely Game", "Isn't it nice");

Then, from the other client we need to request a list of hosts that match our gameType. Since this is a prototype we’re just going to connect to the first instance we get, since there should only ever be one.

On pressing the connect button, we call

MasterServer.RequestHostList(gameType);

Then in our Update we check for hosts returned from the Master Server, and connect to the first one

if ((!connectedToServer) && 
    (MasterServer.PollHostList().Length != 0)) {
    var hosts = MasterServer.PollHostList();
    Network.Connect(hosts[0]);
    Debug.Log("connected to server!");
    connectedToServer = true;
}
Networking in Unity