Sunday 3 March 2013

Easy Property Syncing over Network in Unity

A while back I was experimenting with network code in Unity. To make syncing variables easier I made something I called a 'NetworkMonoBehaviour'. This makes it easy to do exactly what the titles says, easy property syncing over a network in Unity. So here's how it works:

Properties

So we start with a field and, since we like clean code, we encapsulate it with a property.

Networking

Though now, if we change it, it will only be changed locally. This isn't what we want in a network game. So I wrote some code that makes it possible to do this:
This will change the _speed field locally and tell all connected players to do the same. It will only do it if the speed actually changed to minimize network usage. This is made possible by using my NetworkMonoBehaviour. Instead of deriving from MonoBehaviour you derive from NetworkMonoBehaviour with the classes you want to sync. They are still MonoHebaviours, but now indirectly. This makes it possible to used the a few very useful methods in this class. NetworkChangePropertyIfChangedNetworkChangePropertyAndCallMethodIfChanged these are the most used, and their names should explain what they do.
If you just want to use it, and don't want to know how it works, you can stop reading here. Just download the NetworkMonoBehaviour here.

NetworkMonoBehaviour

This is the entire NetworkMonoBehaviour class:

All of these methods will work with int, float, string, Vector3 and Quaternion. Otherwise an exception will be thrown.
The class is actually pretty simple. After checking if the value actually changed, I check what type the variable is (int, float, string, ...) Then I cann the correct RPC. These RPC's are methods that get called on all connected peers, and I made one for every type, which changes a field based on it's name.


Voila, now you can easily sync your properties over a network.
Thanks for reading!