Class NetworkServer | Multiplayer HLAPI | 1.0.8
docs.unity3d.com
    Show / Hide Table of Contents

    Class 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.

    Inheritance
    Object
    NetworkServer
    Namespace: UnityEngine.Networking
    Syntax
    [Obsolete("The high level API classes are deprecated and will be removed in the future.")]
    public sealed class NetworkServer

    Properties

    active

    Checks if the server has been started.

    This will be true after NetworkServer.Listen() has been called.

    Declaration
    public static bool active { get; }
    Property Value
    Type Description
    Boolean

    connections

    A list of all the current connections from clients.

    The connections in the list are at the index of their connectionId. There may be nulls in this list for disconnected clients.

    Declaration
    public static ReadOnlyCollection<NetworkConnection> connections { get; }
    Property Value
    Type Description
    ReadOnlyCollection<NetworkConnection>

    dontListen

    If you enable this, the server will not listen for incoming connections on the regular network port.

    This can be used if the game is running in host mode and does not want external players to be able to connect - making it like a single-player game. Also this can be useful when using AddExternalConnection().

    Declaration
    public static bool dontListen { get; set; }
    Property Value
    Type Description
    Boolean

    handlers

    Dictionary of the message handlers registered with the server.

    The key to the dictionary is the message Id.

    Declaration
    public static Dictionary<short, NetworkMessageDelegate> handlers { get; }
    Property Value
    Type Description
    Dictionary<Int16, NetworkMessageDelegate>

    hostTopology

    The host topology that the server is using.

    This is read-only once the server is started.

    Declaration
    public static HostTopology hostTopology { get; }
    Property Value
    Type Description
    HostTopology

    listenPort

    The port that the server is listening on.

    Declaration
    public static int listenPort { get; }
    Property Value
    Type Description
    Int32

    localClientActive

    True is a local client is currently active on the server.

    This will be true for "Hosts" on hosted server games.

    Declaration
    public static bool localClientActive { get; }
    Property Value
    Type Description
    Boolean

    localConnections

    A list of local connections on the server.

    Declaration
    public static List<NetworkConnection> localConnections { get; }
    Property Value
    Type Description
    List<NetworkConnection>

    maxDelay

    The maximum delay before sending packets on connections.

    In seconds. The default of 0.01 seconds means packets will be delayed at most by 10 milliseconds. Setting this to zero will disable HLAPI connection buffering.

    Declaration
    public static float maxDelay { get; set; }
    Property Value
    Type Description
    Single

    networkConnectionClass

    The class to be used when creating new network connections.

    This can be set with SetNetworkConnectionClass. This allows custom classes that do special processing of data from the transport layer to be used with the NetworkServer.

    See NetworkConnection.TransportSend and NetworkConnection.TransportReceive for details.

    Declaration
    public static Type networkConnectionClass { get; }
    Property Value
    Type Description
    Type

    numChannels

    The number of channels the network is configure with.

    Declaration
    public static int numChannels { get; }
    Property Value
    Type Description
    Int32

    objects

    This is a dictionary of networked objects that have been spawned on the server.

    The key to the dictionary is NetworkIdentity netId.

    Declaration
    public static Dictionary<NetworkInstanceId, NetworkIdentity> objects { get; }
    Property Value
    Type Description
    Dictionary<NetworkInstanceId, NetworkIdentity>

    sendPeerInfo

    Declaration
    [Obsolete("Moved to NetworkMigrationManager")]
    public static bool sendPeerInfo { get; set; }
    Property Value
    Type Description
    Boolean

    serverHostId

    The transport layer hostId used by this server.

    Declaration
    public static int serverHostId { get; }
    Property Value
    Type Description
    Int32

    useWebSockets

    This makes the server listen for WebSockets connections instead of normal transport layer connections.

    This allows WebGL clients to connect to this server. Note that WebGL clients cannot listen for WebSocket connections, they can only make outgoing WebSockets connections.

    Declaration
    public static bool useWebSockets { get; set; }
    Property Value
    Type Description
    Boolean

    Methods

    AddExternalConnection(NetworkConnection)

    This accepts a network connection from another external source and adds it to the server.

    This connection will use the callbacks registered with the server, and can have players added to it like any other connection.

    Declaration
    public static bool AddExternalConnection(NetworkConnection conn)
    Parameters
    Type Name Description
    NetworkConnection conn

    Network connection to add.

    Returns
    Type Description
    Boolean

    True if added.

    AddPlayerForConnection(NetworkConnection, GameObject, Int16)

    When an AddPlayer message handler has received a request from a player, the server calls this to associate the player object with the connection.

    When a player is added for a connection, the client for that connection is made ready automatically. The player object is automatically spawned, so you do not need to call NetworkServer.Spawn for that object. This function is used for "adding" a player, not for "replacing" the player on a connection. If there is already a player on this playerControllerId for this connection, this will fail.

    using UnityEngine;
    using UnityEngine.Networking;
    
    class MyServer : MonoBehaviour
    {
       public GameObject playerPrefab;
    
       void Start()
       {
           NetworkServer.RegisterHandler(MsgType.AddPlayer, OnAddPlayerMessage);
       }
    
       void OnAddPlayerMessage(NetworkMessage netMsg)
       {
           GameObject thePlayer = (GameObject)Instantiate(playerPrefab, Vector3.zero, Quaternion.identity);
           // This spawns the new player on all clients
           NetworkServer.AddPlayerForConnection(conn, thePlayer, 0);
       }
    }
    Declaration
    public static bool AddPlayerForConnection(NetworkConnection conn, GameObject player, short playerControllerId)
    Parameters
    Type Name Description
    NetworkConnection conn

    Connection which is adding the player.

    GameObject player

    Player object spawned for the player.

    Int16 playerControllerId

    The player controller ID number as specified by client.

    Returns
    Type Description
    Boolean

    True if player was added.

    AddPlayerForConnection(NetworkConnection, GameObject, Int16, NetworkHash128)

    Declaration
    public static bool AddPlayerForConnection(NetworkConnection conn, GameObject player, short playerControllerId, NetworkHash128 assetId)
    Parameters
    Type Name Description
    NetworkConnection conn
    GameObject player
    Int16 playerControllerId
    NetworkHash128 assetId
    Returns
    Type Description
    Boolean

    BecomeHost(NetworkClient, Int32, MatchInfo, Int32, PeerInfoMessage[])

    This allows a client that has been disconnected from a server, to become the host of a new version of the game.

    Declaration
    public static NetworkClient BecomeHost(NetworkClient oldClient, int port, MatchInfo matchInfo, int oldConnectionId, PeerInfoMessage[] peers)
    Parameters
    Type Name Description
    NetworkClient oldClient

    The client that was connected to the old host.

    Int32 port

    The port to listen on.

    MatchInfo matchInfo

    Match information (may be null).

    Int32 oldConnectionId
    PeerInfoMessage[] peers
    Returns
    Type Description
    NetworkClient

    ClearHandlers()

    Clear all registered callback handlers.

    Declaration
    public static void ClearHandlers()

    ClearLocalObjects()

    This clears all of the networked objects that the server is aware of. This can be required if a scene change deleted all of the objects without destroying them in the normal manner.

    Declaration
    public static void ClearLocalObjects()

    ClearSpawners()

    Clears all registered spawn prefab and spawn handler functions for this server.

    Declaration
    public static void ClearSpawners()

    Configure(ConnectionConfig, Int32)

    This configures the transport layer settings for the server.

    using UnityEngine;
    using UnityEngine.Networking;
    
    public class Example : MonoBehaviour
    {
       void StartServer()
       {
           ConnectionConfig config = new ConnectionConfig();
           config.AddChannel(QosType.ReliableSequenced);
           config.AddChannel(QosType.UnreliableSequenced);
           config.PacketSize = 500;
           NetworkServer.Configure(config, 10);
           NetworkServer.Listen(7070);
       }
    }
    Declaration
    public static bool Configure(ConnectionConfig config, int maxConnections)
    Parameters
    Type Name Description
    ConnectionConfig config

    Transport layer confuration object.

    Int32 maxConnections

    The maximum number of client connections to allow.

    Returns
    Type Description
    Boolean

    True if successfully configured.

    Configure(HostTopology)

    This configures the transport layer settings for the server.

    using UnityEngine;
    using UnityEngine.Networking;
    
    public class Example : MonoBehaviour
    {
       void StartServer()
       {
           ConnectionConfig config = new ConnectionConfig();
           config.AddChannel(QosType.ReliableSequenced);
           config.AddChannel(QosType.UnreliableSequenced);
           config.PacketSize = 500;
           NetworkServer.Configure(config, 10);
           NetworkServer.Listen(7070);
       }
    }
    Declaration
    public static bool Configure(HostTopology topology)
    Parameters
    Type Name Description
    HostTopology topology

    Transport layer topology object to use.

    Returns
    Type Description
    Boolean

    True if successfully configured.

    Destroy(GameObject)

    Destroys this object and corresponding objects on all clients.

    In some cases it is useful to remove an object but not delete it on the server. For that, use NetworkServer.UnSpawn() instead of NetworkServer.Destroy().

    Declaration
    public static void Destroy(GameObject obj)
    Parameters
    Type Name Description
    GameObject obj

    Game object to destroy.

    DestroyPlayersForConnection(NetworkConnection)

    This destroys all the player objects associated with a NetworkConnections on a server.

    This is used when a client disconnects, to remove the players for that client. This also destroys non-player objects that have client authority set for this connection.

    Declaration
    public static void DestroyPlayersForConnection(NetworkConnection conn)
    Parameters
    Type Name Description
    NetworkConnection conn

    The connections object to clean up for.

    DisconnectAll()

    Disconnect all currently connected clients.

    This can only be called on the server. Clients will receive the Disconnect message.

    using UnityEngine;
    using UnityEngine.Networking;
    
    public class Example : MonoBehaviour
    {
       enum GameState
       {
           kInit,
           kStart
       }
       GameState state;
    
       public void Update()
       {
           if (state != GameState.kInit)
           {
               if (Input.GetKey(KeyCode.Escape))
               {
                   Debug.Log("Disconnecting all!");
                   NetworkServer.DisconnectAll();
                   Application.LoadLevel("empty");
                   state = GameState.kStart;
               }
           }
       }
    }
    Declaration
    public static void DisconnectAll()

    FindLocalObject(NetworkInstanceId)

    This finds the local NetworkIdentity object with the specified network Id.

    Since netIds are the same on the server and all clients for a game, this allows clients to send a netId of a local game objects, and have the server find the corresponding server object.

    Declaration
    public static GameObject FindLocalObject(NetworkInstanceId netId)
    Parameters
    Type Name Description
    NetworkInstanceId netId

    The netId of the NetworkIdentity object to find.

    Returns
    Type Description
    GameObject

    The game object that matches the netId.

    GetConnectionStats()

    Gets aggregate packet stats for all connections.

    Declaration
    public static Dictionary<short, NetworkConnection.PacketStat> GetConnectionStats()
    Returns
    Type Description
    Dictionary<Int16, NetworkConnection.PacketStat>

    Dictionary of msg types and packet statistics.

    GetStatsIn(out Int32, out Int32)

    Get inbound network statistics for the server.

    Declaration
    public static void GetStatsIn(out int numMsgs, out int numBytes)
    Parameters
    Type Name Description
    Int32 numMsgs

    Number of messages received so far.

    Int32 numBytes

    Number of bytes received so far.

    GetStatsOut(out Int32, out Int32, out Int32, out Int32)

    Get outbound network statistics for the client.

    Declaration
    public static void GetStatsOut(out int numMsgs, out int numBufferedMsgs, out int numBytes, out int lastBufferedPerSecond)
    Parameters
    Type Name Description
    Int32 numMsgs

    Number of messages sent so far (including collated messages send through buffer).

    Int32 numBufferedMsgs

    Number of messages sent through buffer.

    Int32 numBytes

    Number of bytes sent so far.

    Int32 lastBufferedPerSecond

    Number of messages buffered for sending per second.

    Listen(Int32)

    Start the server on the given port number. Note that if a match has been created, this will listen using the Relay server instead of a local socket.

    using UnityEngine;
    using UnityEngine.Networking;
    
    public class Manager : MonoBehaviour
    {
       bool isAtStartup = true;
    
       void Update()
       {
           if (Input.GetKeyDown(KeyCode.S) && isAtStartup)
           {
               NetworkServer.Listen(4444);
               NetworkServer.RegisterHandler(MsgType.Ready, OnPlayerReadyMessage);
               isAtStartup = false;
           }
       }
    
       public void OnPlayerReadyMessage(NetworkMessage netMsg)
       {
           // TODO: create player and call PlayerIsReady()
       }
    }
    Declaration
    public static bool Listen(int serverPort)
    Parameters
    Type Name Description
    Int32 serverPort

    Listen port number.

    Returns
    Type Description
    Boolean

    True if listen succeeded.

    Listen(String, Int32)

    Declaration
    public static bool Listen(string ipAddress, int serverPort)
    Parameters
    Type Name Description
    String ipAddress
    Int32 serverPort
    Returns
    Type Description
    Boolean

    Listen(MatchInfo, Int32)

    Declaration
    public static bool Listen(MatchInfo matchInfo, int listenPort)
    Parameters
    Type Name Description
    MatchInfo matchInfo
    Int32 listenPort
    Returns
    Type Description
    Boolean

    ListenRelay(String, Int32, NetworkID, SourceID, NodeID)

    Starts a server using a Relay server. This is the manual way of using the Relay server, as the regular NetworkServer.Connect() will automatically use the Relay server if a match exists.

    Declaration
    public static void ListenRelay(string relayIp, int relayPort, NetworkID netGuid, SourceID sourceId, NodeID nodeId)
    Parameters
    Type Name Description
    String relayIp

    Relay server IP Address.

    Int32 relayPort

    Relay server port.

    NetworkID netGuid

    GUID of the network to create.

    SourceID sourceId

    This server's sourceId.

    NodeID nodeId

    The node to join the network with.

    RegisterHandler(Int16, NetworkMessageDelegate)

    Register a handler for a particular message type.

    There are several system message types which you can add handlers for. You can also add your own message types.

    using UnityEngine;
    using UnityEngine.Networking;
    
    public class MyServer : NetworkManager
    {
       void Start()
       {
           Debug.Log("Registering server callbacks");
           NetworkServer.RegisterHandler(MsgType.Connect, OnConnected);
       }
    
       void OnConnected(NetworkMessage netMsg)
       {
           Debug.Log("Client connected");
       }
    }

    The system message types are listed below:

    class MsgType
    {
       public const short ObjectDestroy = 1;
       public const short Rpc = 2;
       public const short ObjectSpawn = 3;
       public const short Owner = 4;
       public const short Command = 5;
       public const short LocalPlayerTransform = 6;
       public const short SyncEvent = 7;
       public const short UpdateVars = 8;
       public const short SyncList = 9;
       public const short ObjectSpawnScene = 10;
       public const short NetworkInfo = 11;
       public const short SpawnFinished = 12;
       public const short ObjectHide = 13;
       public const short CRC = 14;
       public const short LocalClientAuthority = 15;
    }

    Most of these messages are for internal use only. Users should not define message ids in this range.

    Declaration
    public static void RegisterHandler(short msgType, NetworkMessageDelegate handler)
    Parameters
    Type Name Description
    Int16 msgType

    Message type number.

    NetworkMessageDelegate handler

    Function handler which will be invoked for when this message type is received.

    RemoveExternalConnection(Int32)

    This removes an external connection added with AddExternalConnection().

    Declaration
    public static void RemoveExternalConnection(int connectionId)
    Parameters
    Type Name Description
    Int32 connectionId

    The id of the connection to remove.

    ReplacePlayerForConnection(NetworkConnection, GameObject, Int16)

    This replaces the player object for a connection with a different player object. The old player object is not destroyed.

    If a connection already has a player object, this can be used to replace that object with a different player object. This does NOT change the ready state of the connection, so it can safely be used while changing scenes.

    Declaration
    public static bool ReplacePlayerForConnection(NetworkConnection conn, GameObject player, short playerControllerId)
    Parameters
    Type Name Description
    NetworkConnection conn

    Connection which is adding the player.

    GameObject player

    Player object spawned for the player.

    Int16 playerControllerId

    The player controller ID number as specified by client.

    Returns
    Type Description
    Boolean

    True if player was replaced.

    ReplacePlayerForConnection(NetworkConnection, GameObject, Int16, NetworkHash128)

    Declaration
    public static bool ReplacePlayerForConnection(NetworkConnection conn, GameObject player, short playerControllerId, NetworkHash128 assetId)
    Parameters
    Type Name Description
    NetworkConnection conn
    GameObject player
    Int16 playerControllerId
    NetworkHash128 assetId
    Returns
    Type Description
    Boolean

    Reset()

    Reset the NetworkServer singleton.

    Declaration
    public static void Reset()

    ResetConnectionStats()

    Resets the packet stats on all connections.

    Declaration
    public static void ResetConnectionStats()

    SendByChannelToAll(Int16, MessageBase, Int32)

    Sends a network message to all connected clients on a specified transport layer QoS channel.

    Declaration
    public static bool SendByChannelToAll(short msgType, MessageBase msg, int channelId)
    Parameters
    Type Name Description
    Int16 msgType

    The message id.

    MessageBase msg

    The message to send.

    Int32 channelId

    The transport layer channel to use.

    Returns
    Type Description
    Boolean

    True if the message was sent.

    SendByChannelToReady(GameObject, Int16, MessageBase, Int32)

    Sends a network message to all connected clients that are "ready" on a specified transport layer QoS channel.

    Declaration
    public static bool SendByChannelToReady(GameObject contextObj, short msgType, MessageBase msg, int channelId)
    Parameters
    Type Name Description
    GameObject contextObj

    An object to use for context when calculating object visibility. If null, then the message is sent to all ready clients.

    Int16 msgType

    The message id.

    MessageBase msg

    The message to send.

    Int32 channelId

    The transport layer channel to send on.

    Returns
    Type Description
    Boolean

    True if the message was sent.

    SendBytesToPlayer(GameObject, Byte[], Int32, Int32)

    This sends an array of bytes to a specific player.

    This bypasses the usual serialization and message structures, allowing raw bytes to be send to a player. The contents will be processed as a message on the client of the player, so it must be structured properly.

    Declaration
    public static void SendBytesToPlayer(GameObject player, byte[] buffer, int numBytes, int channelId)
    Parameters
    Type Name Description
    GameObject player

    The player to send the bytes to.

    Byte[] buffer

    Array of bytes to send.

    Int32 numBytes

    Size of array.

    Int32 channelId

    Transport layer channel id to send bytes on.

    SendBytesToReady(GameObject, Byte[], Int32, Int32)

    This sends an array of bytes to all ready players.

    This bypasses the usual serialization and message structures, allowing raw bytes to be send to all ready players. The contents will be processed as a message on the client of the player, so it must be structured properly.

    Declaration
    public static void SendBytesToReady(GameObject contextObj, byte[] buffer, int numBytes, int channelId)
    Parameters
    Type Name Description
    GameObject contextObj
    Byte[] buffer

    Array of bytes to send.

    Int32 numBytes

    Size of array.

    Int32 channelId

    Transport layer channel id to send bytes on.

    SendNetworkInfo(NetworkConnection)

    Declaration
    [Obsolete("moved to NetworkMigrationManager")]
    public void SendNetworkInfo(NetworkConnection targetConnection)
    Parameters
    Type Name Description
    NetworkConnection targetConnection

    SendToAll(Int16, MessageBase)

    Send a message structure with the given type number to all connected clients.

    This applies to clients that are ready and not-ready.

    using UnityEngine;
    using UnityEngine.Networking;
    
    public class MyMessageTypes
    {
       public static short MSG_LOGIN_RESPONSE = 1000;
       public static short MSG_SCORE = 1005;
    };
    
    public class MyScoreMessage : MessageBase
    {
       public int score;
       public Vector3 scorePos;
    }
    
    class GameServer
    {
       void SendScore(int score, Vector3 scorePos)
       {
           MyScoreMessage msg = new MyScoreMessage();
           msg.score = score;
           msg.scorePos = scorePos;
           NetworkServer.SendToAll(MyMessageTypes.MSG_SCORE, msg);
       }
    }
    Declaration
    public static bool SendToAll(short msgType, MessageBase msg)
    Parameters
    Type Name Description
    Int16 msgType

    Message type.

    MessageBase msg

    Message structure.

    Returns
    Type Description
    Boolean

    SendToClient(Int32, Int16, MessageBase)

    Send a message to the client which owns the given connection ID.

    It accepts the connection ID as a parameter as well as a message and MsgType. Remember to set the client up for receiving the messages by using NetworkClient.RegisterHandler. Also, for user messages you must use a MsgType with a higher ID number than MsgType.Highest.

    //The code shows how to set up a message, the MsgType and how to get the connectionID.
    //It also shows how to send the message to the client, as well as receive it.
    //Attach this script to a GameObject
    
    using UnityEngine;
    using UnityEngine.Networking;
    using UnityEngine.Networking.NetworkSystem;
    
    //Create a class for the message you send to the Client
    public class RegisterHostMessage : MessageBase
    {
       public string m_Name;
       public string m_Comment;
    }
    
    public class Example : NetworkManager
    {
       RegisterHostMessage m_Message;
       //This is the Message Type you want to send to the Client. User messages must be above the Highest Message Type.
       public const short m_MessageType = MsgType.Highest + 1;
    
       //Detect when a client connects to the Server
       public override void OnServerConnect(NetworkConnection connection)
       {
           //Change the message to read the Player's connection ID and a comment
           EditMessage("Player " + connection.connectionId, "Hi there.");
           //Send the new message to the Client using the Server
           NetworkServer.SendToClient(connection.connectionId, m_MessageType, m_Message);
       }
    
       //On the Client's side, detect when it connects to a Server
       public override void OnClientConnect(NetworkConnection connection)
       {
           //Register and receive the message on the Client's side
           client.RegisterHandler(m_MessageType, ReceiveMessage);
       }
    
       //Use this to edit the message to read what you want
       void EditMessage(string myName, string myComment)
       {
           m_Message = new RegisterHostMessage();
           //Change the message name and comment to be the ones you set
           m_Message.m_Name = myName;
           m_Message.m_Comment = myComment;
       }
    
       //Use this to receive the message from the Server on the Client's side
       public void ReceiveMessage(NetworkMessage networkMessage)
       {
           //Read the message that comes in
           RegisterHostMessage hostMessage = networkMessage.ReadMessage<RegisterHostMessage>();
           //Store the name and comment as variables
           string receivedName = hostMessage.m_Name;
           string receivedComment = hostMessage.m_Comment;
           //Output the Player name and comment
           Debug.Log("Player Name : " + receivedName);
           Debug.Log("Player Comment : " + receivedComment);
       }
    }
    Declaration
    public static void SendToClient(int connectionId, short msgType, MessageBase msg)
    Parameters
    Type Name Description
    Int32 connectionId

    Client connection ID.

    Int16 msgType

    Message struct to send.

    MessageBase msg

    Message type.

    SendToClientOfPlayer(GameObject, Int16, MessageBase)

    Send a message to the client which owns the given player object instance.

    This function is not very efficient. It is better to send a message directly on the connection object of the player - which can be obtained from the "connectionToClient" member variable on NetworkBehaviour components.

    Declaration
    public static void SendToClientOfPlayer(GameObject player, short msgType, MessageBase msg)
    Parameters
    Type Name Description
    GameObject player

    The players game object.

    Int16 msgType

    Message type.

    MessageBase msg

    Message struct.

    SendToReady(GameObject, Int16, MessageBase)

    Send a message structure with the given type number to only clients which are ready.

    See Networking.NetworkClient.Ready.

    using UnityEngine;
    using UnityEngine.Networking;
    
    public class ReadyMsgTypes
    {
       public static short MSG_LOGIN_RESPONSE = 1000;
       public static short MSG_SCORE = 1005;
    };
    
    public class ReadyScoreMessage : MessageBase
    {
       public int score;
       public Vector3 scorePos;
    }
    
    class GameServer
    {
       public GameObject gameObject;
    
       void SendScore(int score, Vector3 scorePos)
       {
           ReadyScoreMessage msg = new ReadyScoreMessage();
           msg.score = score;
           msg.scorePos = scorePos;
           NetworkServer.SendToReady(gameObject, ReadyMsgTypes.MSG_SCORE, msg);
       }
    }
    Declaration
    public static bool SendToReady(GameObject contextObj, short msgType, MessageBase msg)
    Parameters
    Type Name Description
    GameObject contextObj
    Int16 msgType

    Message type.

    MessageBase msg

    Message structure.

    Returns
    Type Description
    Boolean

    Success if message is sent.

    SendUnreliableToAll(Int16, MessageBase)

    Send given message structure as an unreliable message to all connected clients.

    using UnityEngine;
    using UnityEngine.Networking;
    
    public class UnreliableMsgTypes
    {
       public static short MSG_LOGIN_RESPONSE = 1000;
       public static short MSG_SCORE = 1005;
    };
    
    public class UnreliableScoreMessage : MessageBase
    {
       public int score;
       public Vector3 scorePos;
    }
    
    class GameServer
    {
       void SendScore(int score, Vector3 scorePos)
       {
           UnreliableScoreMessage msg = new UnreliableScoreMessage();
           msg.score = score;
           msg.scorePos = scorePos;
           NetworkServer.SendUnreliableToAll(UnreliableMsgTypes.MSG_SCORE, msg);
       }
    }
    Declaration
    public static bool SendUnreliableToAll(short msgType, MessageBase msg)
    Parameters
    Type Name Description
    Int16 msgType

    Message type.

    MessageBase msg

    Message structure.

    Returns
    Type Description
    Boolean

    Success if message is sent.

    SendUnreliableToReady(GameObject, Int16, MessageBase)

    Send given message structure as an unreliable message only to ready clients.

    See Networking.NetworkClient.Ready.

    using UnityEngine;
    using UnityEngine.Networking;
    
    public class UnreliableMessageTypes
    {
       public static short MSG_LOGIN_RESPONSE = 1000;
       public static short MSG_SCORE = 1005;
    };
    
    public class UnreliableMessage : MessageBase
    {
       public int score;
       public Vector3 scorePos;
    }
    
    class GameServer
    {
       public GameObject gameObject;
    
       void SendScore(int score, Vector3 scorePos)
       {
           UnreliableMessage msg = new UnreliableMessage();
           msg.score = score;
           msg.scorePos = scorePos;
           NetworkServer.SendUnreliableToReady(gameObject, UnreliableMessageTypes.MSG_SCORE, msg);
       }
    }
    Declaration
    public static bool SendUnreliableToReady(GameObject contextObj, short msgType, MessageBase msg)
    Parameters
    Type Name Description
    GameObject contextObj
    Int16 msgType

    Message type.

    MessageBase msg

    Message structure.

    Returns
    Type Description
    Boolean

    Success if message is sent.

    SendWriterToReady(GameObject, NetworkWriter, Int32)

    Sends the contents of a NetworkWriter object to the ready players.

    Declaration
    public static void SendWriterToReady(GameObject contextObj, NetworkWriter writer, int channelId)
    Parameters
    Type Name Description
    GameObject contextObj
    NetworkWriter writer

    The writer object to send.

    Int32 channelId

    The QoS channel to send the data on.

    SetAllClientsNotReady()

    Marks all connected clients as no longer ready.

    All clients will no longer be sent state synchronization updates. The player's clients can call ClientManager.Ready() again to re-enter the ready state. This is useful when switching scenes.

    Declaration
    public static void SetAllClientsNotReady()

    SetClientNotReady(NetworkConnection)

    Sets the client of the connection to be not-ready.

    Clients that are not ready do not receive spawned objects or state synchronization updates. They client can be made ready again by calling SetClientReady().

    Declaration
    public static void SetClientNotReady(NetworkConnection conn)
    Parameters
    Type Name Description
    NetworkConnection conn

    The connection of the client to make not ready.

    SetClientReady(NetworkConnection)

    Sets the client to be ready.

    When a client has signaled that it is ready, this method tells the server that the client is ready to receive spawned objects and state synchronization updates. This is usually called in a handler for the SYSTEM_READY message. If there is not specific action a game needs to take for this message, relying on the default ready handler function is probably fine, so this call wont be needed.

    Declaration
    public static void SetClientReady(NetworkConnection conn)
    Parameters
    Type Name Description
    NetworkConnection conn

    The connection of the client to make ready.

    SetNetworkConnectionClass<T>()

    This sets the class used when creating new network connections.

    The class must be derived from NetworkConnection.

    Declaration
    public static void SetNetworkConnectionClass<T>()
        where T : NetworkConnection
    Type Parameters
    Name Description
    T

    Shutdown()

    This shuts down the server and disconnects all clients.

    Declaration
    public static void Shutdown()

    Spawn(GameObject)

    Spawn the given game object on all clients which are ready.

    This will cause a new object to be instantiated from the registered prefab, or from a custom spawn function.

    //Attach this script to the GameObject you would like to be spawned.
    //Attach a NetworkIdentity component to your GameObject. Click and drag the GameObject into the Assets directory so that it becomes a prefab.
    //The GameObject you assign in the Inspector spawns when the Client connects. To spawn a prefab GameObject, use Instantiate first before spawning the GameObject.
    
    using UnityEngine;
    using UnityEngine.Networking;
    
    public class Example : NetworkBehaviour
    {
       //Assign the prefab in the Inspector
       public GameObject m_MyGameObject;
       GameObject m_MyInstantiated;
    
       void Start()
       {
           //Instantiate the prefab
           m_MyInstantiated = Instantiate(m_MyGameObject);
           //Spawn the GameObject you assign in the Inspector
           NetworkServer.Spawn(m_MyInstantiated);
       }
    }
    Declaration
    public static void Spawn(GameObject obj)
    Parameters
    Type Name Description
    GameObject obj

    Game object with NetworkIdentity to spawn.

    Spawn(GameObject, NetworkHash128)

    Declaration
    public static void Spawn(GameObject obj, NetworkHash128 assetId)
    Parameters
    Type Name Description
    GameObject obj
    NetworkHash128 assetId

    SpawnObjects()

    This causes NetworkIdentity objects in a scene to be spawned on a server.

    NetworkIdentity objects in a scene are disabled by default. Calling SpawnObjects() causes these scene objects to be enabled and spawned. It is like calling NetworkServer.Spawn() for each of them.

    Declaration
    public static bool SpawnObjects()
    Returns
    Type Description
    Boolean

    Success if objects where spawned.

    SpawnWithClientAuthority(GameObject, GameObject)

    This spawns an object like NetworkServer.Spawn() but also assigns Client Authority to the specified client.

    This is the same as calling NetworkIdentity.AssignClientAuthority on the spawned object.

    using UnityEngine;
    using UnityEngine.Networking;
    
    class TestBehaviour : NetworkBehaviour
    {
       public GameObject otherPrefab;
       [Command]
       public void CmdSpawn()
       {
           GameObject go = (GameObject)Instantiate(otherPrefab, transform.position + new Vector3(0, 1, 0), Quaternion.identity);
           NetworkServer.SpawnWithClientAuthority(go, connectionToClient);
       }
    }
    Declaration
    public static bool SpawnWithClientAuthority(GameObject obj, GameObject player)
    Parameters
    Type Name Description
    GameObject obj

    The object to spawn.

    GameObject player

    The player object to set Client Authority to.

    Returns
    Type Description
    Boolean

    SpawnWithClientAuthority(GameObject, NetworkConnection)

    This spawns an object like NetworkServer.Spawn() but also assigns Client Authority to the specified client.

    This is the same as calling NetworkIdentity.AssignClientAuthority on the spawned object.

    using UnityEngine;
    using UnityEngine.Networking;
    
    class TestBehaviour : NetworkBehaviour
    {
       public GameObject otherPrefab;
       [Command]
       public void CmdSpawn()
       {
           GameObject go = (GameObject)Instantiate(otherPrefab, transform.position + new Vector3(0, 1, 0), Quaternion.identity);
           NetworkServer.SpawnWithClientAuthority(go, connectionToClient);
       }
    }
    Declaration
    public static bool SpawnWithClientAuthority(GameObject obj, NetworkConnection conn)
    Parameters
    Type Name Description
    GameObject obj

    The object to spawn.

    NetworkConnection conn

    The connection to set Client Authority to.

    Returns
    Type Description
    Boolean

    SpawnWithClientAuthority(GameObject, NetworkHash128, NetworkConnection)

    This spawns an object like NetworkServer.Spawn() but also assigns Client Authority to the specified client.

    This is the same as calling NetworkIdentity.AssignClientAuthority on the spawned object.

    using UnityEngine;
    using UnityEngine.Networking;
    
    class TestBehaviour : NetworkBehaviour
    {
       public GameObject otherPrefab;
       [Command]
       public void CmdSpawn()
       {
           GameObject go = (GameObject)Instantiate(otherPrefab, transform.position + new Vector3(0, 1, 0), Quaternion.identity);
           NetworkServer.SpawnWithClientAuthority(go, connectionToClient);
       }
    }
    Declaration
    public static bool SpawnWithClientAuthority(GameObject obj, NetworkHash128 assetId, NetworkConnection conn)
    Parameters
    Type Name Description
    GameObject obj

    The object to spawn.

    NetworkHash128 assetId

    The assetId of the object to spawn. Used for custom spawn handlers.

    NetworkConnection conn

    The connection to set Client Authority to.

    Returns
    Type Description
    Boolean

    UnregisterHandler(Int16)

    Unregisters a handler for a particular message type.

    Declaration
    public static void UnregisterHandler(short msgType)
    Parameters
    Type Name Description
    Int16 msgType

    The message type to remove the handler for.

    UnSpawn(GameObject)

    This takes an object that has been spawned and un-spawns it.

    The object will be removed from clients that it was spawned on, or the custom spawn handler function on the client will be called for the object.

    Unlike when calling NetworkServer.Destroy(), on the server the object will NOT be destroyed. This allows the server to re-use the object, even spawn it again later.

    Declaration
    public static void UnSpawn(GameObject obj)
    Parameters
    Type Name Description
    GameObject obj

    The spawned object to be unspawned.

    In This Article
    • Properties
      • active
      • connections
      • dontListen
      • handlers
      • hostTopology
      • listenPort
      • localClientActive
      • localConnections
      • maxDelay
      • networkConnectionClass
      • numChannels
      • objects
      • sendPeerInfo
      • serverHostId
      • useWebSockets
    • Methods
      • AddExternalConnection(NetworkConnection)
      • AddPlayerForConnection(NetworkConnection, GameObject, Int16)
      • AddPlayerForConnection(NetworkConnection, GameObject, Int16, NetworkHash128)
      • BecomeHost(NetworkClient, Int32, MatchInfo, Int32, PeerInfoMessage[])
      • ClearHandlers()
      • ClearLocalObjects()
      • ClearSpawners()
      • Configure(ConnectionConfig, Int32)
      • Configure(HostTopology)
      • Destroy(GameObject)
      • DestroyPlayersForConnection(NetworkConnection)
      • DisconnectAll()
      • FindLocalObject(NetworkInstanceId)
      • GetConnectionStats()
      • GetStatsIn(out Int32, out Int32)
      • GetStatsOut(out Int32, out Int32, out Int32, out Int32)
      • Listen(Int32)
      • Listen(String, Int32)
      • Listen(MatchInfo, Int32)
      • ListenRelay(String, Int32, NetworkID, SourceID, NodeID)
      • RegisterHandler(Int16, NetworkMessageDelegate)
      • RemoveExternalConnection(Int32)
      • ReplacePlayerForConnection(NetworkConnection, GameObject, Int16)
      • ReplacePlayerForConnection(NetworkConnection, GameObject, Int16, NetworkHash128)
      • Reset()
      • ResetConnectionStats()
      • SendByChannelToAll(Int16, MessageBase, Int32)
      • SendByChannelToReady(GameObject, Int16, MessageBase, Int32)
      • SendBytesToPlayer(GameObject, Byte[], Int32, Int32)
      • SendBytesToReady(GameObject, Byte[], Int32, Int32)
      • SendNetworkInfo(NetworkConnection)
      • SendToAll(Int16, MessageBase)
      • SendToClient(Int32, Int16, MessageBase)
      • SendToClientOfPlayer(GameObject, Int16, MessageBase)
      • SendToReady(GameObject, Int16, MessageBase)
      • SendUnreliableToAll(Int16, MessageBase)
      • SendUnreliableToReady(GameObject, Int16, MessageBase)
      • SendWriterToReady(GameObject, NetworkWriter, Int32)
      • SetAllClientsNotReady()
      • SetClientNotReady(NetworkConnection)
      • SetClientReady(NetworkConnection)
      • SetNetworkConnectionClass<T>()
      • Shutdown()
      • Spawn(GameObject)
      • Spawn(GameObject, NetworkHash128)
      • SpawnObjects()
      • SpawnWithClientAuthority(GameObject, GameObject)
      • SpawnWithClientAuthority(GameObject, NetworkConnection)
      • SpawnWithClientAuthority(GameObject, NetworkHash128, NetworkConnection)
      • UnregisterHandler(Int16)
      • UnSpawn(GameObject)
    Back to top
    Copyright © 2023 Unity Technologies — Terms of use
    • Legal
    • Privacy Policy
    • Cookies
    • Do Not Sell or Share My Personal Information
    • Your Privacy Choices (Cookie Settings)
    "Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
    Generated by DocFX on 18 October 2023