Class 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.
Inherited Members
Namespace: UnityEngine.Networking
Syntax
[RequireComponent(typeof(NetworkIdentity))]
[AddComponentMenu("")]
[Obsolete("The high level API classes are deprecated and will be removed in the future.")]
public class NetworkBehaviour : MonoBehaviour
Properties
connectionToClient
The NetworkConnection associated with this NetworkIdentity This is only valid for player objects on the server.
//Attach this script to a GameObject
//Attach a TextMesh to the GameObject. To do this click the GameObject, click the Add Component button in the Inspector window, and go to Mesh>Text Mesh.
//Attach a NetworkIdentity to the GameObject by clicking Add Component, then go to Network>NetworkIdentity. In the component that was added, check the Local Player Authority checkbox.
//Next, create an empty GameObject. Attach a NetworkManager to it by clicking the GameObject, clicking Add Component going to Network>NetworkManager. Also add a NetworkManagerHUD the same way.
//This script outputs the Connection ID and address to the console when the Client is started
using UnityEngine;
using UnityEngine.Networking;
public class ConnectionToClientExample : NetworkBehaviour
{
//This is a TextMesh component that you attach to the child of the NetworkIdentity GameObject
TextMesh m_TextMesh;
void Start()
{
//Output the connection ID and IP address of the connection by using connectionToClient
Debug.Log("Connection ID : " + connectionToClient.connectionId);
Debug.Log("Connection Address : " + connectionToClient.address);
//Check that the connection is marked as ready
if (connectionToClient.isReady)
{
Debug.Log("Ready!");
}
//Enter the child of your GameObject (the GameObject with the TextMesh you attach)
//Fetch the TextMesh component of it
m_TextMesh = GetComponentInChildren(typeof(TextMesh)) as TextMesh;
//Change the Text of the TextMesh to show the netId
m_TextMesh.text = "ID : " + netId;
//Output the connection to Client
}
}
Declaration
public NetworkConnection connectionToClient { get; }
Property Value
Type | Description |
---|---|
NetworkConnection |
connectionToServer
The NetworkConnection associated with this NetworkIdentity This is only valid for player objects on the server.
Declaration
public NetworkConnection connectionToServer { get; }
Property Value
Type | Description |
---|---|
NetworkConnection |
hasAuthority
This returns true if this object is the authoritative version of the object in the distributed network application.
The localPlayerAuthority value on the NetworkIdentity determines how authority is determined. For most objects, authority is held by the server / host. For objects with localPlayerAuthority set, authority is held by the client of that player.
Declaration
public bool hasAuthority { get; }
Property Value
Type | Description |
---|---|
Boolean |
isClient
Returns true if running as a client and this object was spawned by a server.
Declaration
public bool isClient { get; }
Property Value
Type | Description |
---|---|
Boolean |
isLocalPlayer
This returns true if this object is the one that represents the player on the local machine.
In multiplayer games, there are multiple instances of the Player object. The client needs to know which one is for "themselves" so that only that player processes input and potentially has a camera attached. The IsLocalPlayer function will return true only for the player instance that belongs to the player on the local machine, so it can be used to filter out input for non-local players.
This example shows processing input for only the local player.
using UnityEngine;
using UnityEngine.Networking;
public class Player : NetworkBehaviour
{
int moveX = 0;
int moveY = 0;
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]
void CmdMove(int dx, int dy)
{
// move here
}
}
Declaration
public bool isLocalPlayer { get; }
Property Value
Type | Description |
---|---|
Boolean |
isServer
Returns true if this object is active on an active server.
This is only true if the object has been spawned. This is different from NetworkServer.active, which is true if the server itself is active rather than this object being active.
Declaration
public bool isServer { get; }
Property Value
Type | Description |
---|---|
Boolean |
localPlayerAuthority
This value is set on the NetworkIdentity and is accessible here for convenient access for scripts.
Declaration
public bool localPlayerAuthority { get; }
Property Value
Type | Description |
---|---|
Boolean |
netId
The unique network Id of this object.
This is assigned at runtime by the network server and will be unique for all objects for that network session.
Declaration
public NetworkInstanceId netId { get; }
Property Value
Type | Description |
---|---|
NetworkInstanceId |
playerControllerId
The id of the player associated with the behaviour.
This is only valid if the GameObject is a local player.
The HLAPI treats players and clients as separate GameObjects. In most cases, there is a single player for each client, but in some situations (for example, when there are multiple controllers connected to a console system) there might be multiple player GameObjects for a single connection. When there are multiple players for a single connection, use the playerControllerId property to tell them apart. This is an identifier that is scoped to the connection, so that it maps to the id of the controller associated with the player on that client.
Declaration
public short playerControllerId { get; }
Property Value
Type | Description |
---|---|
Int16 |
syncVarDirtyBits
Declaration
protected uint syncVarDirtyBits { get; }
Property Value
Type | Description |
---|---|
UInt32 |
syncVarHookGuard
Declaration
protected bool syncVarHookGuard { get; set; }
Property Value
Type | Description |
---|---|
Boolean |
Methods
ClearAllDirtyBits()
This clears all the dirty bits that were set on this script by SetDirtyBits();
This is automatically invoked when an update is sent for this object, but can be called manually as well.
Declaration
public void ClearAllDirtyBits()
GetNetworkChannel()
This virtual function is used to specify the QoS channel to use for SyncVar updates for this script.
Using the NetworkSettings custom attribute causes this function to be implemented for this script, but developers can also implement it themselves.
Declaration
public virtual int GetNetworkChannel()
Returns
Type | Description |
---|---|
Int32 | The QoS channel for this script. |
GetNetworkSendInterval()
This virtual function is used to specify the send interval to use for SyncVar updates for this script.
Using the NetworkSettings custom attribute causes this function to be implemented for this script, but developers can also implement it themselves.
Declaration
public virtual float GetNetworkSendInterval()
Returns
Type | Description |
---|---|
Single | The time in seconds between updates. |
InvokeCommand(Int32, NetworkReader)
Manually invoke a Command.
Declaration
public virtual bool InvokeCommand(int cmdHash, NetworkReader reader)
Parameters
Type | Name | Description |
---|---|---|
Int32 | cmdHash | Hash of the Command name. |
NetworkReader | reader | Parameters to pass to the command. |
Returns
Type | Description |
---|---|
Boolean | Returns true if successful. |
InvokeRPC(Int32, NetworkReader)
Manually invoke an RPC function.
Declaration
public virtual bool InvokeRPC(int cmdHash, NetworkReader reader)
Parameters
Type | Name | Description |
---|---|---|
Int32 | cmdHash | Hash of the RPC name. |
NetworkReader | reader | Parameters to pass to the RPC function. |
Returns
Type | Description |
---|---|
Boolean | Returns true if successful. |
InvokeSyncEvent(Int32, NetworkReader)
Manually invoke a SyncEvent.
Declaration
public virtual bool InvokeSyncEvent(int cmdHash, NetworkReader reader)
Parameters
Type | Name | Description |
---|---|---|
Int32 | cmdHash | Hash of the SyncEvent name. |
NetworkReader | reader | Parameters to pass to the SyncEvent. |
Returns
Type | Description |
---|---|
Boolean | Returns true if successful. |
InvokeSyncList(Int32, NetworkReader)
Declaration
public virtual bool InvokeSyncList(int cmdHash, NetworkReader reader)
Parameters
Type | Name | Description |
---|---|---|
Int32 | cmdHash | |
NetworkReader | reader |
Returns
Type | Description |
---|---|
Boolean |
OnCheckObserver(NetworkConnection)
Callback used by the visibility system to determine if an observer (player) can see this object.
If this function returns true, the network connection will be added as an observer.
Declaration
public virtual bool OnCheckObserver(NetworkConnection conn)
Parameters
Type | Name | Description |
---|---|---|
NetworkConnection | conn | Network connection of a player. |
Returns
Type | Description |
---|---|
Boolean | True if the player can see this object. |
OnDeserialize(NetworkReader, Boolean)
Virtual function to override to receive custom serialization data. The corresponding function to send serialization data is OnSerialize().
Declaration
public virtual void OnDeserialize(NetworkReader reader, bool initialState)
Parameters
Type | Name | Description |
---|---|---|
NetworkReader | reader | Reader to read from the stream. |
Boolean | initialState | True if being sent initial state. |
OnNetworkDestroy()
This is invoked on clients when the server has caused this object to be destroyed.
This can be used as a hook to invoke effects or do client specific cleanup.
using UnityEngine;
using UnityEngine.Networking;
class Bomb : NetworkBehaviour
{
public override void OnNetworkDestroy()
{
// play explosion sound
}
}
Declaration
public virtual void OnNetworkDestroy()
OnRebuildObservers(HashSet<NetworkConnection>, Boolean)
Callback used by the visibility system to (re)construct the set of observers that can see this object.
Implementations of this callback should add network connections of players that can see this object to the observers set.
Declaration
public virtual bool OnRebuildObservers(HashSet<NetworkConnection> observers, bool initialize)
Parameters
Type | Name | Description |
---|---|---|
HashSet<NetworkConnection> | observers | The new set of observers for this object. |
Boolean | initialize | True if the set of observers is being built for the first time. |
Returns
Type | Description |
---|---|
Boolean | Return true if this function did work. |
OnSerialize(NetworkWriter, Boolean)
Virtual function to override to send custom serialization data. The corresponding function to send serialization data is OnDeserialize().
The initialState flag is useful to differentiate between the first time an object is serialized and when incremental updates can be sent. The first time an object is sent to a client, it must include a full state snapshot, but subsequent updates can save on bandwidth by including only incremental changes. Note that SyncVar hook functions are not called when initialState is true, only for incremental updates.
If a class has SyncVars, then an implementation of this function and OnDeserialize() are added automatically to the class. So a class that has SyncVars cannot also have custom serialization functions.
The OnSerialize function should return true to indicate that an update should be sent. If it returns true, then the dirty bits for that script are set to zero, if it returns false then the dirty bits are not changed. This allows multiple changes to a script to be accumulated over time and sent when the system is ready, instead of every frame.
Declaration
public virtual bool OnSerialize(NetworkWriter writer, bool initialState)
Parameters
Type | Name | Description |
---|---|---|
NetworkWriter | writer | Writer to use to write to the stream. |
Boolean | initialState | If this is being called to send initial state. |
Returns
Type | Description |
---|---|
Boolean | True if data was written. |
OnSetLocalVisibility(Boolean)
Callback used by the visibility system for objects on a host.
Objects on a host (with a local client) cannot be disabled or destroyed when they are not visibile to the local client. So this function is called to allow custom code to hide these objects. A typical implementation will disable renderer components on the object. This is only called on local clients on a host.
Declaration
public virtual void OnSetLocalVisibility(bool vis)
Parameters
Type | Name | Description |
---|---|---|
Boolean | vis | New visibility state. |
OnStartAuthority()
Declaration
public virtual void OnStartAuthority()
OnStartClient()
Called on every NetworkBehaviour when it is activated on a client.
Objects on the host have this function called, as there is a local client on the host. The values of SyncVars on object are guaranteed to be initialized correctly with the latest state from the server when this function is called on the client.
Declaration
public virtual void OnStartClient()
OnStartLocalPlayer()
Called when the local player object has been set up.
This happens after OnStartClient(), as it is triggered by an ownership message from the server. This is an appropriate place to activate components or functionality that should only be active for the local player, such as cameras and input.
Declaration
public virtual void OnStartLocalPlayer()
OnStartServer()
This is invoked for NetworkBehaviour objects when they become active on the server.
This could be triggered by NetworkServer.Listen() for objects in the scene, or by NetworkServer.Spawn() for objects that are dynamically created.
This will be called for objects on a "host" as well as for object on a dedicated server.
Declaration
public virtual void OnStartServer()
OnStopAuthority()
This is invoked on behaviours when authority is removed.
When NetworkIdentity.RemoveClientAuthority is called on the server, this will be called on the client that owns the object.
Declaration
public virtual void OnStopAuthority()
PreStartClient()
An internal method called on client objects to resolve GameObject references.
It is not safe to put user code in this function as it may be replaced by the network system's code generation process.
Declaration
public virtual void PreStartClient()
RegisterCommandDelegate(Type, Int32, NetworkBehaviour.CmdDelegate)
Declaration
protected static void RegisterCommandDelegate(Type invokeClass, int cmdHash, NetworkBehaviour.CmdDelegate func)
Parameters
Type | Name | Description |
---|---|---|
Type | invokeClass | |
Int32 | cmdHash | |
NetworkBehaviour.CmdDelegate | func |
RegisterEventDelegate(Type, Int32, NetworkBehaviour.CmdDelegate)
Declaration
protected static void RegisterEventDelegate(Type invokeClass, int cmdHash, NetworkBehaviour.CmdDelegate func)
Parameters
Type | Name | Description |
---|---|---|
Type | invokeClass | |
Int32 | cmdHash | |
NetworkBehaviour.CmdDelegate | func |
RegisterRpcDelegate(Type, Int32, NetworkBehaviour.CmdDelegate)
Declaration
protected static void RegisterRpcDelegate(Type invokeClass, int cmdHash, NetworkBehaviour.CmdDelegate func)
Parameters
Type | Name | Description |
---|---|---|
Type | invokeClass | |
Int32 | cmdHash | |
NetworkBehaviour.CmdDelegate | func |
RegisterSyncListDelegate(Type, Int32, NetworkBehaviour.CmdDelegate)
Declaration
protected static void RegisterSyncListDelegate(Type invokeClass, int cmdHash, NetworkBehaviour.CmdDelegate func)
Parameters
Type | Name | Description |
---|---|---|
Type | invokeClass | |
Int32 | cmdHash | |
NetworkBehaviour.CmdDelegate | func |
SendCommandInternal(NetworkWriter, Int32, String)
Declaration
protected void SendCommandInternal(NetworkWriter writer, int channelId, string cmdName)
Parameters
Type | Name | Description |
---|---|---|
NetworkWriter | writer | |
Int32 | channelId | |
String | cmdName |
SendEventInternal(NetworkWriter, Int32, String)
Declaration
protected void SendEventInternal(NetworkWriter writer, int channelId, string eventName)
Parameters
Type | Name | Description |
---|---|---|
NetworkWriter | writer | |
Int32 | channelId | |
String | eventName |
SendRPCInternal(NetworkWriter, Int32, String)
Declaration
protected void SendRPCInternal(NetworkWriter writer, int channelId, string rpcName)
Parameters
Type | Name | Description |
---|---|---|
NetworkWriter | writer | |
Int32 | channelId | |
String | rpcName |
SendTargetRPCInternal(NetworkConnection, NetworkWriter, Int32, String)
Declaration
protected void SendTargetRPCInternal(NetworkConnection conn, NetworkWriter writer, int channelId, string rpcName)
Parameters
Type | Name | Description |
---|---|---|
NetworkConnection | conn | |
NetworkWriter | writer | |
Int32 | channelId | |
String | rpcName |
SetDirtyBit(UInt32)
Used to set the behaviour as dirty, so that a network update will be sent for the object.
Declaration
public void SetDirtyBit(uint dirtyBit)
Parameters
Type | Name | Description |
---|---|---|
UInt32 | dirtyBit | Bit mask to set. |
SetSyncVar<T>(T, ref T, UInt32)
Declaration
protected void SetSyncVar<T>(T value, ref T fieldValue, uint dirtyBit)
Parameters
Type | Name | Description |
---|---|---|
T | value | |
T | fieldValue | |
UInt32 | dirtyBit |
Type Parameters
Name | Description |
---|---|
T |
SetSyncVarGameObject(GameObject, ref GameObject, UInt32, ref NetworkInstanceId)
Declaration
protected void SetSyncVarGameObject(GameObject newGameObject, ref GameObject gameObjectField, uint dirtyBit, ref NetworkInstanceId netIdField)
Parameters
Type | Name | Description |
---|---|---|
GameObject | newGameObject | |
GameObject | gameObjectField | |
UInt32 | dirtyBit | |
NetworkInstanceId | netIdField |