We already had the proto file that define the messages and the server side is already written so all I needed was ProtoBuf implementation for .NET. The main problem is that most C# libraries for ProtoBuf either use attributes and not proto files or they use reflection which is not supported in Ahead-Of-Time (AOT) environment like Unity3D on iOS.
After some research I decide to use ProtoBuf C# Code Generator project by Peter Hultqvist. The main difference between this and other ProtoBuf implementations is that this one create C# code that does not use reflection and does not depend on binary libraries. It generate 3 files:
- The clean messages file that contain only the properties of each message
- The somewhat messy serialization/deserialization counterpart of each message.
- Helper classes
I use this library on Mac OS X with mono and it run without a problem. It generate clean code that you can easily read.
The few minor issues I did find were quickly (2 hours) fixed by Peter.
Things to note
Api Compatibility Level
One important notice for Unity3D developers: because the current generated code uses InvalidDataException which is not part of .NET 2.0 subset. If you don't to the following change the project will fail when building iOS XCode project with error message that not explain what is wrong.
You must do the following before exporting to iOS XCode project:
- Open Build Settings window
- Select iOS
- Click Player Settings... button
- Under Optimization section change Api Compatibility Level to .NET 2.0
Reading Message
If you want to read message from a socket you will need to wrap your Socket instance with NetworkStream and then wrap that with SilentOrbit.ProtocolBuffers.StreamRead. This might be confusing because there is already StreamReader class in .NET, I point that to Peter and I'm sure he will find other name.
If you don't wrap your NetworkStream with StreamRead you'll find that the underlying code uses Position property which is off course not available in NetworkStream.
No comments:
Post a Comment