Namespace UnityEngine.Networking
Classes
Channels
Class containing constants for default network channels.
ClientAttribute
A Custom Attribute that can be added to member functions of NetworkBehaviour scripts, to make them only run on clients.
A [Client] method returns immediately if NetworkClient.active is not true, and generates a warning on the console. This attribute can be put on member functions that are meant to be only called on clients. This would redundant for [ClientRPC] functions, as being client-only is already enforced for them.
using UnityEngine;
using UnityEngine.Networking;
public class Example : MonoBehaviour
{
[Client]
public void OnClientDisconnected(NetworkConnection conn, NetworkReader reader)
{
Debug.Log("Client Disconnected");
//ShutdownGame();
Application.LoadLevel("title");
}
}
ClientCallbackAttribute
A Custom Attribute that can be added to member functions of NetworkBehaviour scripts, to make them only run on clients, but not generate warnings.
This custom attribute is the same as the Client custom attribute, except that it does not generate a warning in the console if called on a server. This is useful to avoid spamming the console for functions that will be invoked by the engine, such as Update() or physics callbacks.
using UnityEngine;
using UnityEngine.Networking;
public class Example : MonoBehaviour
{
[ClientCallback]
void OnTriggerEnter2D(Collider2D collider)
{
// make explosion
}
}
ClientRpcAttribute
ClientScene
A client manager which contains static client information and functions.
This manager contains references to tracked static local objects such as spawner registrations. It also has the default message handlers used by clients when they registered none themselves. The manager handles adding/removing player objects to the game after a client connection has been set as ready.
The ClientScene is a singleton, and it has static convenience methods such as ClientScene.Ready().
The ClientScene is used by the NetworkManager, but it can be used by itself.
As the ClientScene manages player objects on the client, it is where clients request to add players. The NetworkManager does this via the ClientScene automatically when auto-add-players is set, but it can be done through code using the function ClientScene.AddPlayer(). This sends an AddPlayer message to the server and will cause a player object to be created for this client.
Like NetworkServer, the ClientScene understands the concept of the local client. The function ClientScene.ConnectLocalServer() is used to become a host by starting a local client (when a server is already running).
CommandAttribute
This is an attribute that can be put on methods of NetworkBehaviour classes to allow them to be invoked on the server by sending a command from a client.
[Command] functions are invoked on the player GameObject associated with a connection. This is set up in response to the "ready" message, by passing the player GameObject to the NetworkServer.PlayerIsReady() function. The arguments to the command call are serialized across the network, so that the server function is invoked with the same values as the function on the client. These functions must begin with the prefix "Cmd" and cannot be static.
using UnityEngine;
using UnityEngine.Networking;
public class Player : NetworkBehaviour
{
int moveX = 0;
int moveY = 0;
float moveSpeed = 0.2f;
bool isDirty = false;
void Update()
{
if (!isLocalPlayer)
{
return;
}
// input handling for local player only
int oldMoveX = moveX;
int oldMoveY = moveY;
moveX = 0;
moveY = 0;
if (Input.GetKey(KeyCode.LeftArrow))
{
moveX -= 1;
}
if (Input.GetKey(KeyCode.RightArrow))
{
moveX += 1;
}
if (Input.GetKey(KeyCode.UpArrow))
{
moveY += 1;
}
if (Input.GetKey(KeyCode.DownArrow))
{
moveY -= 1;
}
if (moveX != oldMoveX || moveY != oldMoveY)
{
CmdMove(moveX, moveY);
}
}
[Command]
public void CmdMove(int x, int y)
{
moveX = x;
moveY = y;
isDirty = true;
}
public void FixedUpdate()
{
if (NetworkServer.active)
{
transform.Translate(moveX * moveSpeed, moveY * moveSpeed, 0);
}
}
}
The allowed argument types are;
- Basic type (byte, int, float, string, UInt64, etc)
- Built-in Unity math type (Vector3, Quaternion, etc),
- Arrays of basic types
- Structs containing allowable types
- NetworkIdentity
- NetworkInstanceId
- NetworkHash128
- GameObject with a NetworkIdentity component attached.
LogFilter
FilterLog is a utility class that controls the level of logging generated by UNET clients and servers.
MessageBase
Network message classes should be derived from this class. These message classes can then be sent using the various Send functions of NetworkConnection, NetworkClient and NetworkServer.
Public data fields of classes derived from MessageBase will be automatically serialized with the class. The virtual methods Serialize and Deserialize may be implemented by developers for precise control, but if they are not implemented, then implementations will be generated for them.
Note : Unity uses its own network serialization system. It doesn't support the NonSerialized attribute. Instead, use private variables.
In the example below, the methods have implementations, but if those methods were not implemented, the message would still be usable.
using UnityEngine;
using UnityEngine.Networking;
class SpawnMessage : MessageBase
{
public uint netId;
public NetworkHash128 assetId;
public Vector3 position;
public byte[] payload;
// This method would be generated
public override void Deserialize(NetworkReader reader)
{
netId = reader.ReadPackedUInt32();
assetId = reader.ReadNetworkHash128();
position = reader.ReadVector3();
payload = reader.ReadBytesAndSize();
}
// This method would be generated
public override void Serialize(NetworkWriter writer)
{
writer.WritePackedUInt32(netId);
writer.Write(assetId);
writer.Write(position);
writer.WriteBytesFull(payload);
}
}
MsgType
Container class for networking system built-in message types.
NetworkAnimator
A component to synchronize Mecanim animation states for networked objects.
The animation of game objects can be networked by this component. There are two models of authority for networked movement:
If the object has authority on the client, then it should animated locally on the owning client. The animation state information will be sent from the owning client to the server, then broadcast to all of the other clients. This is common for player objects.
If the object has authority on the server, then it should be animated on the server and state information will be sent to all clients. This is common for objects not related to a specific client, such as an enemy unit.
The NetworkAnimator synchronizes the animation parameters that are checked in the inspector view. It does not automatically sychronize triggers. The function SetTrigger can by used by an object with authority to fire an animation trigger on other clients.
NetworkBehaviour
Base class which should be inherited by scripts which contain networking functionality.
This is a MonoBehaviour class so scripts which need to use the networking feature should inherit this class instead of MonoBehaviour. It allows you to invoke networked actions, receive various callbacks, and automatically synchronize state from server-to-client.
The NetworkBehaviour component requires a NetworkIdentity on the game object. There can be multiple NetworkBehaviours on a single game object. For an object with sub-components in a hierarchy, the NetworkIdentity must be on the root object, and NetworkBehaviour scripts must also be on the root object.
Some of the built-in components of the networking system are derived from NetworkBehaviour, including NetworkTransport, NetworkAnimator and NetworkProximityChecker.
NetworkBehaviour.Invoker
NetworkCallbacks
NetworkClient
This is a network client class used by the networking system. It contains a NetworkConnection that is used to connect to a network server.
The NetworkClient handle connection state, messages handlers, and connection configuration. There can be many NetworkClient instances in a process at a time, but only one that is connected to a game server (NetworkServer) that uses spawned objects.
NetworkClient has an internal update function where it handles events from the transport layer. This includes asynchronous connect events, disconnect events and incoming data from a server.
The NetworkManager has a NetworkClient instance that it uses for games that it starts, but the NetworkClient may be used by itself.
NetworkConnection
A High level network connection. This is used for connections from client-to-server and for connection from server-to-client.
A NetworkConnection corresponds to a specific connection for a host in the transport layer. It has a connectionId that is assigned by the transport layer and passed to the Initialize function.
A NetworkClient has one NetworkConnection. A NetworkServerSimple manages multiple NetworkConnections. The NetworkServer has multiple "remote" connections and a "local" connection for the local client.
The NetworkConnection class provides message sending and handling facilities. For sending data over a network, there are methods to send message objects, byte arrays, and NetworkWriter objects. To handle data arriving from the network, handler functions can be registered for message Ids, byte arrays can be processed by HandleBytes(), and NetworkReader object can be processed by HandleReader().
NetworkConnection objects also act as observers for networked objects. When a connection is an observer of a networked object with a NetworkIdentity, then the object will be visible to corresponding client for the connection, and incremental state changes will be sent to the client.
NetworkConnection objects can "own" networked game objects. Owned objects will be destroyed on the server by default when the connection is destroyed. A connection owns the player objects created by its client, and other objects with client-authority assigned to the corresponding client.
There are many virtual functions on NetworkConnection that allow its behaviour to be customized. NetworkClient and NetworkServer can both be made to instantiate custom classes derived from NetworkConnection by setting their networkConnectionClass member variable.
NetworkConnection.PacketStat
Structure used to track the number and size of packets of each packets type.
NetworkCRC
This class holds information about which networked scripts use which QoS channels for updates.
This channel information is used to ensure that clients and servers are using compatible HLAPI script configurations.
NetworkDiscovery
The NetworkDiscovery component allows Unity games to find each other on a local network. It can broadcast presence and listen for broadcasts, and optionally join matching games using the NetworkManager.
This component can run in server mode (by calling StartAsServer) where it broadcasts to other computers on the local network, or in client mode (by calling StartAsClient) where it listens for broadcasts from a server. This class should be override to receive calls from OnReceivedBroadcast.
Note : Do not use void Update() in a class that inherits from NetworkDiscovery. If needed, you must override it and call base.Update() instead.
using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
public class OverriddenNetworkDiscovery : NetworkDiscovery
{
public override void OnReceivedBroadcast(string fromAddress, string data)
{
NetworkManager.singleton.networkAddress = fromAddress;
NetworkManager.singleton.StartClient();
}
}
NetworkIdentity
The NetworkIdentity identifies objects across the network, between server and clients. Its primary data is a NetworkInstanceId which is allocated by the server and then set on clients. This is used in network communications to be able to lookup game objects on different machines.
The NetworkIdentity is used to synchronize information in the object with the network. Only the server should create instances of objects which have NetworkIdentity as otherwise they will not be properly connected to the system.
For complex objects with a hierarchy of subcomponents, the NetworkIdentity must be on the root of the hierarchy. It is not supported to have multiple NetworkIdentity components on subcomponents of a hierarchy.
NetworkBehaviour scripts require a NetworkIdentity on the game object to be able to function.
The NetworkIdentity manages the dirty state of the NetworkBehaviours of the object. When it discovers that NetworkBehaviours are dirty, it causes an update packet to be created and sent to clients.
The flow for serialization updates managed by the NetworkIdentity is:
* Each NetworkBehaviour has a dirty mask. This mask is available inside OnSerialize as syncVarDirtyBits
* Each SyncVar in a NetworkBehaviour script is assigned a bit in the dirty mask.
* Changing the value of SyncVars causes the bit for that SyncVar to be set in the dirty mask
* Alternatively, calling SetDirtyBit() writes directly to the dirty mask
* NetworkIdentity objects are checked on the server as part of it's update loop
* If any NetworkBehaviours on a NetworkIdentity are dirty, then an UpdateVars packet is created for that object
* The UpdateVars packet is populated by calling OnSerialize on each NetworkBehaviour on the object
* NetworkBehaviours that are NOT dirty write a zero to the packet for their dirty bits
* NetworkBehaviours that are dirty write their dirty mask, then the values for the SyncVars that have changed
* If OnSerialize returns true for a NetworkBehaviour, the dirty mask is reset for that NetworkBehaviour, so it will not send again until its value changes.
* The UpdateVars packet is sent to ready clients that are observing the object
On the client:
* an UpdateVars packet is received for an object
* The OnDeserialize function is called for each NetworkBehaviour script on the object
* Each NetworkBehaviour script on the object reads a dirty mask.
* If the dirty mask for a NetworkBehaviour is zero, the OnDeserialize functions returns without reading any more
* If the dirty mask is non-zero value, then the OnDeserialize function reads the values for the SyncVars that correspond to the dirty bits that are set
* If there are SyncVar hook functions, those are invoked with the value read from the stream.
NetworkLobbyManager
This is a specialized NetworkManager that includes a networked lobby.
The lobby has slots that track the joined players, and a maximum player count that is enforced. It requires that the NetworkLobbyPlayer component be on the lobby player objects.
NetworkLobbyManager is derived from NetworkManager, and so it implements many of the virtual functions provided by the NetworkManager class. To avoid accidentally replacing functionality of the NetworkLobbyManager, there are new virtual functions on the NetworkLobbyManager that begin with "OnLobby". These should be used on classes derived from NetworkLobbyManager instead of the virtual functions on NetworkManager.
The OnLobby*() functions have empty implementations on the NetworkLobbyManager base class, so the base class functions do not have to be called.
NetworkLobbyPlayer
This component works in conjunction with the NetworkLobbyManager to make up the multiplayer lobby system.
The LobbyPrefab object of the NetworkLobbyManager must have this component on it. This component holds basic lobby player data required for the lobby to function. Game specific data for lobby players can be put in other components on the LobbyPrefab or in scripts derived from NetworkLobbyPlayer.
NetworkManager
The NetworkManager is a convenience class for the HLAPI for managing networking systems.
For simple network applications the NetworkManager can be used to control the HLAPI. It provides simple ways to start and stop client and servers, to manage scenes, and has virtual functions that user code can use to implement handlers for network events. The NetworkManager deals with one client at a time. The example below shows a minimal network setup.
using UnityEngine;
using UnityEngine.Networking;
public class Manager : NetworkManager
{
public override void OnServerConnect(NetworkConnection conn)
{
Debug.Log("OnPlayerConnected");
}
}
NetworkManagerHUD
An extension for the NetworkManager that displays a default HUD for controlling the network state of the game.
This component also shows useful internal state for the networking system in the inspector window of the editor. It allows users to view connections, networked objects, message handlers, and packet statistics. This information can be helpful when debugging networked games.
NetworkMessage
The details of a network message received by a client or server on a network connection.
NetworkMigrationManager
A component that manages the process of a new host taking over a game when the old host is lost. This is referred to as "host migration". The migration manager sends information about each peer in the game to all the clients, and when the host is lost because of a crash or network outage, the clients are able to choose a new host, and continue the game.
The old host is able to rejoin the new game on the new host.
The state of SyncVars and SyncLists on all objects with NetworkIdentities in the scene is maintained during a host migration. This also applies to custom serialized data for objects.
All of the player objects in the game are disabled when the host is lost. Then, when the other clients rejoin the new game on the new host, the corresponding players for those clients are re-enabled on the host, and respawned on the other clients. No player state data is lost during a host migration.
This class provides a simple default UI for controlling the behaviour when the host is lost. The UI can be disabled with the showGUI property. There are a number of virtual functions that can be implemented to customize the behaviour of host migration.
Note that only data that is available to clients will be preserved during a host migration. If there is data that is only on the server, then it will not be available to the client that becomes the new host. This means data on the host that is not in SyncVars or SyncLists will not be available after a host migration.
The callback function OnStartServer is invoked for all networked objects when the client becomes a new host.
On the new host, the NetworkMigrationManager uses the function NetworkServer.BecomeNewHost() to construct a networked server scene from the state in the current ClientScene.
The peers in a game with host migration enabled are identified by their connectionId on the server. When a client reconnects to the new host of a game, this connectionId is passed to the new host so that it can match this client with the client that was connected to the old host. This Id is set on the ClientScene as the "reconnectId".
The old host of the game, the one that crashed or lost its network connection, can also reconnect to the new game as a client. This client uses the special ReconnectId of ClientScene.ReconnectIdHost (which is zero).
NetworkProximityChecker
Component that controls visibility of networked objects for players.
Any object with this component on it will not be visible to players more than a (configurable) distance away.
NetworkReader
General purpose serializer for UNET (for reading byte arrays).
This class works with NetworkWriter and is used for serializing data for UNet commands, RPC calls, events and low level messages.
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 this 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());
}
}
}
NetworkServer
The NetworkServer uses a NetworkServerSimple for basic network functionality and adds more game-like functionality.
NetworkServer handles remote connections from remote clients via a NetworkServerSimple instance, and also has a local connection for a local client.
The NetworkServer is a singleton. It has static convenience functions such as NetworkServer.SendToAll() and NetworkServer.Spawn() which automatically use the singleton instance.
The NetworkManager uses the NetworkServer, but it can be used without the NetworkManager.
The set of networked objects that have been spawned is managed by NetworkServer. Objects are spawned with NetworkServer.Spawn() which adds them to this set, and makes them be created on clients. Spawned objects are removed automatically when they are destroyed, or than they can be removed from the spawned set by calling NetworkServer.UnSpawn() - this does not destroy the object.
There are a number of internal messages used by NetworkServer, these are setup when NetworkServer.Listen() is called.
NetworkServerSimple
The NetworkServerSimple is a basic server class without the "game" related functionality that the NetworkServer class has.
This class has no scene management, spawning, player objects, observers, or static interface like the NetworkServer class. It is simply a server that listens on a port, manages connections, and handles messages. There can be more than one instance of this class in a process.
Like the NetworkServer and NetworkClient classes, it allows the type of NetworkConnection class created for new connections to be specified with SetNetworkConnectionClass(), so custom types of network connections can be used with it.
This class can be used by overriding the virtual functions OnConnected, OnDisconnected and OnData; or by registering message handlers.
NetworkSettingsAttribute
This attribute is used to configure the network settings of scripts that are derived from the NetworkBehaviour base class.
using UnityEngine.Networking;
[NetworkSettings(channel = 1, sendInterval = 0.2f)]
class MyScript : NetworkBehaviour
{
[SyncVar]
int value;
}
NetworkStartPosition
This component is used to make a gameObject a starting position for spawning player objects in multiplayer games.
This object's transform will be automatically registered and unregistered with the NetworkManager as a starting position.
NetworkTransform
A component to synchronize the position and rotation of networked objects.
The movement of game objects can be networked by this component. There are two models of authority for networked movement:
If the object has authority on the client, then it should be controlled locally on the owning client, then movement state information will be sent from the owning client to the server, then broadcast to all of the other clients. This is common for player objects.
If the object has authority on the server, then it should be controlled on the server and movement state information will be sent to all clients. This is common for objects not related to a specific client, such as an enemy unit.
NetworkTransformChild
A component to synchronize the position of child transforms of networked objects.
There must be a NetworkTransform on the root object of the hierarchy. There can be multiple NetworkTransformChild components on an object. This does not use physics for synchronization, it simply synchronizes the localPosition and localRotation of the child transform and lerps towards the recieved values.
NetworkTransformVisualizer
This is a helper component to help understand and debug networked movement synchronization with the NetworkTransform component.
NetworkWriter
General purpose serializer for UNET (for serializing data to byte arrays).
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 this 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());
}
}
}
PlayerController
This represents a networked player.
ServerAttribute
A Custom Attribute that can be added to member functions of NetworkBehaviour scripts, to make them only run on servers.
A [Server] method returns immediately if NetworkServer.active is not true, and generates a warning on the console. This attribute can be put on member functions that are meant to be only called on server. This would be redundant for Command] functions, as being server-only is already enforced for them.
using UnityEngine;
using UnityEngine.Networking;
public class Example : NetworkBehaviour
{
[Server]
public void Explode()
{
NetworkServer.Destroy(gameObject);
}
}
ServerCallbackAttribute
A Custom Attribute that can be added to member functions of NetworkBehaviour scripts, to make them only run on servers, but not generate warnings.
This custom attribute is the same as the [Server] custom attribute, except that it does not generate a warning in the console if called on a client. This is useful to avoid spamming the console for functions that will be invoked by the engine, such as Update() or physics callbacks.
using UnityEngine;
using UnityEngine.Networking;
public class Example : MonoBehaviour
{
float regenTimer = 0;
int heat = 100;
[ServerCallback]
void Update()
{
// heat dissipates over time
if (Time.time > regenTimer)
{
if (heat > 1)
heat -= 2;
regenTimer = Time.time + 1.0f;
}
}
}
SyncEventAttribute
This is an attribute that can be put on events in NetworkBehaviour classes to allow them to be invoked on client when the event is called on the server.
[SyncEvent] events are called by user code on UNET servers, and then invoked on corresponding client objects on clients connected to the server. The arguments to the Event call are serialized across the network, so that the client event is invoked with the same values as the function on the server. These events must begin with the prefix "Event".
using UnityEngine;
using UnityEngine.Networking;
public class DamageClass : NetworkBehaviour
{
public delegate void TakeDamageDelegate(int amount, float dir);
[SyncEvent]
public event TakeDamageDelegate EventTakeDamage;
[Command]
public void CmdDoMe(int val)
{
EventTakeDamage(val, 1.0f);
}
}
public class Other : NetworkBehaviour
{
public DamageClass damager;
int health = 100;
void Start()
{
if (NetworkClient.active)
damager.EventTakeDamage += TakeDamage;
}
public void TakeDamage(int amount, float dir)
{
health -= amount;
}
}
SyncEvents allow networked actions to be propagated to other scripts attached to the object. In the example above, the Other class registers for the TakeDamage event on the DamageClass. When the event happens on the DamageClass on the server, the TakeDamage() method will be invoked on the Other class on the client object. This allows modular network aware systems to be created, that can be extended by new scripts that respond to the events generated by them.
SyncList<T>
This is the base class for type-specific SyncList classes.
A SyncList can only be of the following type;
- Basic type (byte, int, float, string, UInt64, etc)
- Built-in Unity math type (Vector3, Quaternion, etc),
- NetworkIdentity
- NetworkInstanceId
- NetworkHash128
- GameObject with a NetworkIdentity component attached.
SyncListBool
A list of booleans that will be synchronized from server to clients.
SyncListFloat
A list of floats that will be synchronized from server to clients.
SyncListInt
A list of integers that will be synchronized from server to clients.
SyncListString
This is a list of strings that will be synchronized from the server to clients.
SyncListStruct<T>
This class is used for lists of structs that are synchronized from the server to clients.
To use SyncListStruct, derive a new class with your struct as the generic parameter.
SyncListUInt
A list of unsigned integers that will be synchronized from server to clients.
SyncVarAttribute
[SyncVar] is an attribute that can be put on member variables of NetworkBehaviour classes. These variables will have their values sychronized from the server to clients in the game that are in the ready state.
Setting the value of a [SyncVar] marks it as dirty, so it will be sent to clients at the end of the current frame. Only simple values can be marked as [SyncVars]. The type of the SyncVar variable cannot be from an external DLL or assembly.
using UnityEngine;
using UnityEngine.Networking;
public class Ship : NetworkBehaviour
{
[SyncVar]
public int health = 100;
[SyncVar]
public float energy = 100;
}
The allowed SyncVar types are:
- Basic type (byte, int, float, string, UInt64, etc)
- Built-in Unity math type (Vector3, Quaternion, etc),
- Structs containing allowable types.
TargetRpcAttribute
This is an attribute that can be put on methods of NetworkBehaviour classes to allow them to be invoked on clients from a server. Unlike the ClientRpc attribute, these functions are invoked on one individual target client, not all of the ready clients.
[TargetRpc] functions are called by user code on the server, and then invoked on the corresponding client object on the client of the specified NetworkConnection. The arguments to the RPC call are serialized across the network, so that the client function is invoked with the same values as the function on the server. These functions must begin with the prefix "Target" and cannot be static.
The first argument to an TargetRpc function must be a NetworkConnection object.
using UnityEngine;
using UnityEngine.Networking;
public class Example : NetworkBehaviour
{
[TargetRpc]
public void TargetDoMagic(NetworkConnection target, int extra)
{
Debug.Log("Magic = " + (123 + extra));
}
[Command]
void CmdTest()
{
TargetDoMagic(connectionToClient, 55);
}
}
The allowed argument types are;
- Basic type (byte, int, float, string, UInt64, etc)
- Built-in Unity math type (Vector3, Quaternion, etc),
- Arrays of basic types
- Structs containing allowable types
- NetworkIdentity
- NetworkInstanceId
- NetworkHash128
- GameObject with a NetworkIdentity component attached.
Structs
NetworkBroadcastResult
A structure that contains data from a NetworkDiscovery server broadcast.
NetworkHash128
A 128 bit number used to represent assets in a networking context.
NetworkInstanceId
This is used to identify networked objects across all participants of a network. It is assigned at runtime by the server when an object is spawned.
NetworkMigrationManager.ConnectionPendingPlayers
The player objects for connections to the old host.
This is used when clients reconnect to the new host.
NetworkMigrationManager.PendingPlayerInfo
Information about a player object from another peer.
NetworkSceneId
This is used to identify networked objects in a scene. These values are allocated in the editor and are persistent for the lifetime of the object in the scene.
Interfaces
INetworkTransport
Enums
ChannelOption
An enumeration of the options that can be set on a network channel.
LogFilter.FilterLevel
NetworkBehaviour.UNetInvokeType
NetworkClient.ConnectState
NetworkMigrationManager.SceneChangeOption
An enumeration of how to handle scene changes when the connection to the host is lost.
NetworkProximityChecker.CheckMethod
Enumeration of methods to use to check proximity.
NetworkTransform.AxisSyncMode
An axis or set of axis.
NetworkTransform.CompressionSyncMode
How much to compress sync data.
NetworkTransform.TransformSyncMode
How to synchronize an object's position.
PlayerSpawnMethod
Enumeration of methods of where to spawn player objects in multiplayer games.
using UnityEngine;
using UnityEngine.Networking;
public class PlayerSpawnMethodExample : MonoBehaviour
{
void Update()
{
//Press the space key to switch to spawning on a random spawn point
if (Input.GetKeyDown(KeyCode.Space))
{
//Check that the PlayerSpawnMethod is currently RoundRobin
if (NetworkManager.singleton.playerSpawnMethod == PlayerSpawnMethod.RoundRobin)
//Switch it to Random spawning if it is
NetworkManager.singleton.playerSpawnMethod = PlayerSpawnMethod.Random;
//Otherwise switch it to RoundRobin
else NetworkManager.singleton.playerSpawnMethod = PlayerSpawnMethod.RoundRobin;
}
}
}
SyncList<T>.Operation
The types of operations that can occur for SyncLists.
Version
Enumeration of Networking versions.
Delegates
NetworkBehaviour.CmdDelegate
Delegate for Command functions.
NetworkBehaviour.EventDelegate
Delegate for Event functions.
NetworkIdentity.ClientAuthorityCallback
The delegate type for the clientAuthorityCallback.
NetworkMessageDelegate
NetworkTransform.ClientMoveCallback2D
NetworkTransform.ClientMoveCallback3D
SpawnDelegate
SyncList<T>.SyncListChanged
A delegate that can be populated to recieve callbacks when the list changes.
For example this function is called when the m_ints list changes:
using UnityEngine;
using UnityEngine.Networking;
public class MyBehaviour : NetworkBehaviour
{
public SyncListInt m_ints = new SyncListInt();
private void OnIntChanged(SyncListInt.Operation op, int index)
{
Debug.Log("list changed " + op);
}
public override void OnStartClient()
{
m_ints.Callback = OnIntChanged;
}
}
It is best to populate the delagate during the OnStartClient() callback function. Doing it earlier can lead to it being lost when the initial list value is applied.