Important: UNet is a deprecated solution, and a new Multiplayer and NetworkingThe Unity system that enables multiplayer gaming across a computer network. More info See in Glossary Solution (Netcode for GameObjects) is under development. For more information and next steps see the information on the Unity Netcode for GameObjects website. |
Use the NetworkReader and NetworkWriter classes to write data to byte streams.
The Multiplayer High Level APIA system for building multiplayer capabilities for Unity games. It is built on top of the lower level transport real-time communication layer, and handles many of the common tasks that are required for multiplayer games. More info
See in Glossary is built using these classes, and uses them extensively. However, you can use them directly if you want to implement your own custom transport functionality. They have specific serialization functions for many Unity types (See NetworkWriter.Write for the full list of types).
To use the classes, create a writer instance, and write individual variables into it. These are serialized internally into a byte array, and this can be sent over the network. On the receiving side it’s important that the reader instance for the byte array reads back the variables in exactly the same order they were written in.
This can be used with the MessageBase class to make byte arrays that contain serialized network messages.
void SendMessage(short msgType, MessageBase msg, int channelId)
{
// write the message to a local buffer
NetworkWriter writer = new NetworkWriter();
writer.StartMessage(msgType);
msg.Serialize(writer);
writer.FinishMessage();
myClient.SendWriter(writer, channelId);
}
This message is correctly formatted so that a message handler function can be invoked for it.
The following code sample is a rather low level demonstration, using the lowest level classes from the high-level API for setting up connectivity.
This is the code for connecting the client and server together:
using UnityEngine;
using UnityEngine.Networking;
public class Serializer : MonoBehaviour {
NetworkServerSimple m_Server;
NetworkClient m_Client;
const short k_MyMessage = 100;
// When using a server instance like this it must be pumped manually
void Update() {
if (m_Server != null)
m_Server.Update();
}
void StartServer() {
m_Server = new NetworkServerSimple();
m_Server.RegisterHandler(k_MyMessage, OnMyMessage);
if (m_Server.Listen(5555))
Debug.Log("Started listening on 5555");
}
void StartClient() {
m_Client = new NetworkClient();
m_Client.RegisterHandler(MsgType.Connect, OnClientConnected);
m_Client.Connect("127.0.0.1", 5555);
}
void OnClientConnected(NetworkMessage netmsg) {
Debug.Log("Client connected to server");
SendMessage();
}
}
The next piece of code sends a message using the network reader and network writer, but uses the message handlers built into these classes:
void SendMessage() {
NetworkWriter writer = new NetworkWriter();
writer.StartMessage(k_MyMessage);
writer.Write(42);
writer.Write("What is the answer");
writer.FinishMessage();
m_Client.SendWriter(writer, 0);
}
void OnMyMessage(NetworkMessage netmsg) {
Debug.Log("Got message, size=" + netmsg.reader.Length);
var someValue = netmsg.reader.ReadInt32();
var someString = netmsg.reader.ReadString();
Debug.Log("Message value=" + someValue + " Message string='" + someString + "'");
}
When setting up messages for the message handlers, you should always use NetworkWriter.StartMessage()
(with the message type ID) and NetworkWriter.FinishMessage() calls. When not using the byte arrays, you can skip that step.
When you visit any website, it may store or retrieve information on your browser, mostly in the form of cookies. This information might be about you, your preferences or your device and is mostly used to make the site work as you expect it to. The information does not usually directly identify you, but it can give you a more personalized web experience. Because we respect your right to privacy, you can choose not to allow some types of cookies. Click on the different category headings to find out more and change our default settings. However, blocking some types of cookies may impact your experience of the site and the services we are able to offer.
More information
These cookies enable the website to provide enhanced functionality and personalisation. They may be set by us or by third party providers whose services we have added to our pages. If you do not allow these cookies then some or all of these services may not function properly.
These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site. They help us to know which pages are the most and least popular and see how visitors move around the site. All information these cookies collect is aggregated and therefore anonymous. If you do not allow these cookies we will not know when you have visited our site, and will not be able to monitor its performance.
These cookies may be set through our site by our advertising partners. They may be used by those companies to build a profile of your interests and show you relevant adverts on other sites. They do not store directly personal information, but are based on uniquely identifying your browser and internet device. If you do not allow these cookies, you will experience less targeted advertising. Some 3rd party video providers do not allow video views without targeting cookies. If you are experiencing difficulty viewing a video, you will need to set your cookie preferences for targeting to yes if you wish to view videos from these providers. Unity does not control this.
These cookies are necessary for the website to function and cannot be switched off in our systems. They are usually only set in response to actions made by you which amount to a request for services, such as setting your privacy preferences, logging in or filling in forms. You can set your browser to block or alert you about these cookies, but some parts of the site will not then work. These cookies do not store any personally identifiable information.