How to use protobuf in Unity

 

How to use protobuf in Unity

  17549 people read   comments (0)   collection   report

 

In the development of mobile phone games, Unity3D has become a relatively mainstream development technology.

Then for the unpacking and unpacking of the client-server protocol, we have three common processing methods:

1. Custom structure: directly transfer the custom structure in the code in the protocol; the disadvantage of this method is that it greatly increases the repetitive workload, and cannot achieve forward and backward compatibility of the protocol, and the scalability is poor;

2, json, xml and other text protocol formats: use json, xml and other text protocols as the protocol format; the advantage of this method is that it is easy to develop, facilitates forward and backward compatibility and expansion of the protocol, but the disadvantage is that it cannot be serialized, the amount of data is large, and the bandwidth is wasted ;

3. Recommended method: protobuf protocol unpacking method; protobuf is a set of open source protocols proposed by google, which has good forward and backward protocol compatibility, is easy to expand, and has high serialization and deserialization efficiency. It can greatly reduce the size of the transmitted data;

In Unity3D development, the C# language is generally used for development of the network part. It is generally recommended to use the protobuf-net third-party library for development.

But unfortunately, the JIT technology used in it is not available in the iOS version of Unity3D, and will cause an exception during serialization.

After searching on google, I found an inconvenient solution as follows:

http://www.frictionpointstudios.com/blog/2011/3/31/using-protobuf-net-serialization-in-unity-iphone.html

However, this scheme is very complicated and very inconvenient to operate.

After my own experiments, I found one of the following solutions available:

1. Download the source code of protbuf-net from SVN:

http://protobuf-net.googlecode.com/svn/trunk/protobuf-net

2. Copy all the C# source code in this directory to Unity3D, and use the source code directly instead of the third-party dll;

3. When compiling in Unity at this time, an error may be reported saying that unsafe cannot be used;

4. The solution can be solved by the following solution: Create a new smcs.rsp file under the Assets directory, and write the -unsafe string in it, without adding spaces before and after;

5. Restart Unity, at this time we can find that the project can be compiled;

 

It has been verified that this solution is also available on IOS devices. This ensures that our protobuf can be used in Unity mobile development .

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327000352&siteId=291194637