I’m looking for the simplest way to pass custom classes between the client and server in Unity.
I have a game already built in a different engine that I’m porting to Unity. Fortunately for me the entire server-side is written in C# and is 100% reusable as is. I need to be able to make calls from the Unity client for things like “GetAccountInformation” where the server will make a database call and return a bunch of information to the client about the logged in user’s account. Characters on the account, teams, etc. What is the best way to do this in Unity? I know RPC doesn’t support complex types but is there a workaround there or should I be considering some other avenue?
Unity RPCs support byte parameters. You’ll need to handle serialization / deserialization to / from the byte array for your custom data, but you can use standard C# solutions for that.
Here is a basic example of a pair of functions I added to one of my classes to convert between byte:
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
public static Effect DeserializeFromNetwork(byte[] networkSerializedEffect)
{
MemoryStream stream = new MemoryStream(networkSerializedEffect);
BinaryFormatter binaryFormatter = new BinaryFormatter();
return (Effect)binaryFormatter.Deserialize(stream);
}
public byte[] SerializeForNetwork()
{
MemoryStream stream = new MemoryStream();
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(stream, this);
return stream.GetBuffer();
}
As long as your class and all classes it uses as members have the [Serializable] attribute then you should be good. Only problem I ran into was Vector3 not being serializable, but you could create a wrapper class for it.