用于 UNET 的通用序列化程序(用于将数据序列化为字节数组)。
using UnityEngine; using UnityEngine.Networking;
public class ExampleScript : MonoBehaviour { // Writing data to a NetworkWriter and then // Converting this to a NetworkReader. void Start() { // The data you add to your writer must be prefixed with a message type. // This is in the form of a short. short myMsgType = 143;
NetworkWriter writer = new NetworkWriter();
// You start the message in your writer by passing in the message type. // This is a short meaning that it will take up 2 bytes at the start of // your message. writer.StartMessage(myMsgType);
// You can now begin your message. In this case we will just use strings. writer.Write("Test data 1"); writer.Write("Test data 2"); writer.Write("Test data 3");
// Make sure to end your message with FinishMessage() writer.FinishMessage();
// You can now access the data in your writer. ToArray() returns a copy // of the bytes that the writer is using and AsArray() returns the // internal array of bytes, not a copy. byte[] writerData = writer.ToArray();
CreateNetworkReader(writerData); }
void CreateNetworkReader(byte[] data) { // We will create the NetworkReader using the data from our previous // NetworkWriter. NetworkReader networkReader = new NetworkReader(data);
// The first two bytes in the buffer represent the size // of the message. This is equal to the NetworkReader.Length // minus the size of the prefix. byte[] readerMsgSizeData = networkReader.ReadBytes(2); short readerMsgSize = (short)((readerMsgSizeData[1] << 8) + readerMsgSizeData[0]); Debug.Log(readerMsgSize);
// The message type added in NetworkWriter.StartMessage // is to be read now. It is a short and so consists of // two bytes. It is the second two bytes on the buffer. byte[] readerMsgTypeData = networkReader.ReadBytes(2); short readerMsgType = (short)((readerMsgTypeData[1] << 8) + readerMsgTypeData[0]); Debug.Log(readerMsgType);
// If all of your data is of the same type (in out case the // data on our buffer is comprised of only strings) you can // read all the data from the buffer using a loop like so. while (networkReader.Position < networkReader.Length) { Debug.Log(networkReader.ReadString()); } } }
Position | 内部缓冲区的当前位置。 |
NetworkWriter | 创建一个新的 NetworkWriter 对象。 |
AsArray | 返回编写器使用的内部字节数组。这不是一个副本。 |
FinishMessage | 此函数将填充以 StartMessage() 开头的消息的标头,以便能够使用 Send() 函数发送此消息。 |
SeekZero | 定位内部缓冲区的开头。 |
StartMessage | 此函数启用新消息,写入有效负载后,应使用 FinishMessage() 完成此消息。 |
ToArray | 返回编写器使用的内部字节数组的副本,它仅复制使用的字节。 |
Write | 此函数将引用写入对象、值、缓冲区或网络消息,并与 NetworkIdentity 组件相结合将引用写入流中。 |
WriteBytesAndSize | 此函数将一个 16 位计数和一个同样长度的字节数组写入流中。 |
WriteBytesFull | 此函数将一个 16 位计数和一个同样大小的字节数组写入流中。 |
WritePackedUInt32 | 此函数使用可变长度编码将 32 位值写入流中。 |
WritePackedUInt64 | 此函数使用可变长度编码将 64 位值写入流中。 |