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

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

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

    Fields

    ReconnectIdHost

    A constant ID used by the old host when it reconnects to the new host.

    Declaration
    public const int ReconnectIdHost = 0
    Field Value
    Type Description
    Int32

    ReconnectIdInvalid

    An invalid reconnect Id.

    Declaration
    public const int ReconnectIdInvalid = -1
    Field Value
    Type Description
    Int32

    Properties

    localPlayers

    A list of all players added to the game.

    These are the players on this client, not all of the players in the game on the server. The client has no explicit knowledge of the player objects of other clients.

    Declaration
    public static List<PlayerController> localPlayers { get; }
    Property Value
    Type Description
    List<PlayerController>

    objects

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

    The key of the dictionary is the NetworkIdentity netId of the objects.

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

    prefabs

    This is a dictionary of the prefabs that are registered on the client with ClientScene.RegisterPrefab().

    The key to the dictionary is the prefab asset Id.

    Declaration
    public static Dictionary<NetworkHash128, GameObject> prefabs { get; }
    Property Value
    Type Description
    Dictionary<NetworkHash128, GameObject>

    ready

    Returns true when a client's connection has been set to ready.

    A client that is ready recieves state updates from the server, while a client that is not ready does not. This useful when the state of the game is not normal, such as a scene change or end-of-game.

    This is read-only. To change the ready state of a client, use ClientScene.Ready(). The server is able to set the ready state of clients using NetworkServer.SetClientReady(), NetworkServer.SetClientNotReady() and NetworkServer.SetAllClientsNotReady().

    This is done when changing scenes so that clients don't receive state update messages during scene loading.

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

    readyConnection

    The NetworkConnection object that is currently "ready". This is the connection to the server where objects are spawned from.

    This connection can be used to send messages to the server. There can only be one ready connection at a time. There can be multiple NetworkClient instances in existence, each with their own NetworkConnections, but there is only one ClientScene instance and corresponding ready connection.

    Declaration
    public static NetworkConnection readyConnection { get; }
    Property Value
    Type Description
    NetworkConnection

    reconnectId

    The reconnectId to use when a client reconnects to the new host of a game after the old host was lost.

    This will be ClientScene.ReconnectIdInvalid by default (-1), and will be ClientScene.ReconnectIdHost when the old host is reconnecting to the host of the new game.

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

    spawnableObjects

    This is dictionary of the disabled NetworkIdentity objects in the scene that could be spawned by messages from the server.

    The key to the dictionary is the NetworkIdentity sceneId.

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

    Methods

    AddPlayer(Int16)

    This adds a player GameObject for this client. This causes an AddPlayer message to be sent to the server, and NetworkManager.OnServerAddPlayer is called. If an extra message was passed to AddPlayer, then OnServerAddPlayer will be called with a NetworkReader that contains the contents of the message.

    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. This is not the global player number.

    Declaration
    public static bool AddPlayer(short playerControllerId)
    Parameters
    Type Name Description
    Int16 playerControllerId

    The local player ID number.

    Returns
    Type Description
    Boolean

    True if player was added.

    AddPlayer(NetworkConnection, Int16)

    This adds a player GameObject for this client. This causes an AddPlayer message to be sent to the server, and NetworkManager.OnServerAddPlayer is called. If an extra message was passed to AddPlayer, then OnServerAddPlayer will be called with a NetworkReader that contains the contents of the message.

    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. This is not the global player number.

    Declaration
    public static bool AddPlayer(NetworkConnection readyConn, short playerControllerId)
    Parameters
    Type Name Description
    NetworkConnection readyConn

    The connection to become ready for this client.

    Int16 playerControllerId

    The local player ID number.

    Returns
    Type Description
    Boolean

    True if player was added.

    AddPlayer(NetworkConnection, Int16, MessageBase)

    This adds a player GameObject for this client. This causes an AddPlayer message to be sent to the server, and NetworkManager.OnServerAddPlayer is called. If an extra message was passed to AddPlayer, then OnServerAddPlayer will be called with a NetworkReader that contains the contents of the message.

    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. This is not the global player number.

    Declaration
    public static bool AddPlayer(NetworkConnection readyConn, short playerControllerId, MessageBase extraMessage)
    Parameters
    Type Name Description
    NetworkConnection readyConn

    The connection to become ready for this client.

    Int16 playerControllerId

    The local player ID number.

    MessageBase extraMessage

    An extra message object that can be passed to the server for this player.

    Returns
    Type Description
    Boolean

    True if player was added.

    ClearSpawners()

    This clears the registered spawn prefabs and spawn handler functions for this client.

    Declaration
    public static void ClearSpawners()

    ConnectLocalServer()

    Create and connect a local client instance to the local server. This makes the client into a "host" - a client and server in the same process.

    The returned local client acts like normal remote client but internally all messages are routed directly to the server process. Commands from a local client are executed synchronously on the server.

    Declaration
    public static NetworkClient ConnectLocalServer()
    Returns
    Type Description
    NetworkClient

    A client object for communicating with the local server.

    DestroyAllClientObjects()

    Destroys all networked objects on the client.

    This can be used to clean up when a network connection is closed.

    Declaration
    public static void DestroyAllClientObjects()

    FindLocalObject(NetworkInstanceId)

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

    NetId is a unique number assigned to all objects with NetworkIdentity components in a game. This number is the same on the server and all connected clients for a particular object, so it can be used to identify objects across the network. The FindLocalObject() function is called on a client to transform a netId received from a server to a local game object.

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

    The id of the networked object.

    Returns
    Type Description
    GameObject

    The game object that matches the netId.

    Ready(NetworkConnection)

    Signal that the client connection is ready to enter the game.

    This could be for example when a client enters an ongoing game and has finished loading the current scene. The server should respond to the SYSTEM_READY event with an appropriate handler which instantiates the players object for example.

    using UnityEngine;
    using UnityEngine.UI;
    using UnityEngine.Networking;
    
    //This makes the GameObject a NetworkManager GameObject
    public class Example : NetworkManager
    {
       public bool m_ServerStarted, m_ClientStarted;
       public Button m_ClientButton;
    
    
       //Detect when a client connects to the Server
       public override void OnClientConnect(NetworkConnection connection)
       {
           ClientScene.Ready(connection);
           ClientScene.AddPlayer(0);
           m_ClientStarted = true;
           //Output text to show the connection on the client side
           Debug.Log("Client Side : Client " + connection.connectionId + " Connected!");
           //Register and receive the message on the Client's side (NetworkConnection.Send Example)
           client.RegisterHandler(MsgType.Ready, ReadyMessage);
       }
    
       //Use this to receive the message from the Server on the Client's side
       public void ReadyMessage(NetworkMessage networkMessage)
       {
           Debug.Log("Client Ready! ");
       }
    
       //Detect when a client disconnects from the Server
       public override void OnClientDisconnect(NetworkConnection connection)
       {
           //Change the text to show the connection loss on the client side
           Debug.Log("Client Side : Client " + connection.connectionId + " Lost!");
           m_ClientStarted = false;
       }
       public void ClientButton()
       {
           if (!m_ClientStarted)
           {
               NetworkServer.Reset();
               singleton.StartClient();
               m_ClientButton.GetComponentInChildren<Text>().text = "Disconnect";
           }
           else
           {
               singleton.StopClient();
           }
       }
    }
    Declaration
    public static bool Ready(NetworkConnection conn)
    Parameters
    Type Name Description
    NetworkConnection conn

    The client connection which is ready.

    Returns
    Type Description
    Boolean

    RegisterPrefab(GameObject)

    Registers a prefab with the UNET spawning system.

    When a NetworkIdentity object is spawned on a server with NetworkServer.SpawnObject(), and the prefab that the object was created from was registered with RegisterPrefab(), the client will use that prefab to instantiate a corresponding client object with the same netId.

    The NetworkManager has a list of spawnable prefabs, it uses this function to register those prefabs with the ClientScene.

    The set of current spawnable object is available in the ClientScene static member variable ClientScene.prefabs, which is a dictionary of NetworkAssetIds and prefab references.

    using UnityEngine;
    using UnityEngine.Networking;
    
    public class PlantSpawner : NetworkBehaviour
    {
       public GameObject plantPrefab;
    
       public override void OnStartClient()
       {
           ClientScene.RegisterPrefab(plantPrefab);
       }
    
       [Server]
       public void ServerSpawnPlant(Vector3 pos, Quaternion rot)
       {
           var plant = (GameObject)Instantiate(plantPrefab, pos, rot);
           NetworkServer.Spawn(plant);
       }
    }

    The optional custom spawn and un-spawn handler functions can be used to implement more advanced spawning strategies such as object pools.

    Declaration
    public static void RegisterPrefab(GameObject prefab)
    Parameters
    Type Name Description
    GameObject prefab

    A Prefab that will be spawned.

    RegisterPrefab(GameObject, NetworkHash128)

    Registers a prefab with the UNET spawning system.

    When a NetworkIdentity object is spawned on a server with NetworkServer.SpawnObject(), and the prefab that the object was created from was registered with RegisterPrefab(), the client will use that prefab to instantiate a corresponding client object with the same netId.

    The NetworkManager has a list of spawnable prefabs, it uses this function to register those prefabs with the ClientScene.

    The set of current spawnable object is available in the ClientScene static member variable ClientScene.prefabs, which is a dictionary of NetworkAssetIds and prefab references.

    using UnityEngine;
    using UnityEngine.Networking;
    
    public class PlantSpawner : NetworkBehaviour
    {
       public GameObject plantPrefab;
    
       public override void OnStartClient()
       {
           ClientScene.RegisterPrefab(plantPrefab);
       }
    
       [Server]
       public void ServerSpawnPlant(Vector3 pos, Quaternion rot)
       {
           var plant = (GameObject)Instantiate(plantPrefab, pos, rot);
           NetworkServer.Spawn(plant);
       }
    }

    The optional custom spawn and un-spawn handler functions can be used to implement more advanced spawning strategies such as object pools.

    Declaration
    public static void RegisterPrefab(GameObject prefab, NetworkHash128 newAssetId)
    Parameters
    Type Name Description
    GameObject prefab

    A Prefab that will be spawned.

    NetworkHash128 newAssetId

    An assetId to be assigned to this prefab. This allows a dynamically created game object to be registered for an already known asset Id.

    RegisterPrefab(GameObject, SpawnDelegate, UnSpawnDelegate)

    Registers a prefab with the UNET spawning system.

    When a NetworkIdentity object is spawned on a server with NetworkServer.SpawnObject(), and the prefab that the object was created from was registered with RegisterPrefab(), the client will use that prefab to instantiate a corresponding client object with the same netId.

    The NetworkManager has a list of spawnable prefabs, it uses this function to register those prefabs with the ClientScene.

    The set of current spawnable object is available in the ClientScene static member variable ClientScene.prefabs, which is a dictionary of NetworkAssetIds and prefab references.

    using UnityEngine;
    using UnityEngine.Networking;
    
    public class PlantSpawner : NetworkBehaviour
    {
       public GameObject plantPrefab;
    
       public override void OnStartClient()
       {
           ClientScene.RegisterPrefab(plantPrefab);
       }
    
       [Server]
       public void ServerSpawnPlant(Vector3 pos, Quaternion rot)
       {
           var plant = (GameObject)Instantiate(plantPrefab, pos, rot);
           NetworkServer.Spawn(plant);
       }
    }

    The optional custom spawn and un-spawn handler functions can be used to implement more advanced spawning strategies such as object pools.

    Declaration
    public static void RegisterPrefab(GameObject prefab, SpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler)
    Parameters
    Type Name Description
    GameObject prefab

    A Prefab that will be spawned.

    SpawnDelegate spawnHandler

    A method to use as a custom spawnhandler on clients.

    UnSpawnDelegate unspawnHandler

    A method to use as a custom un-spawnhandler on clients.

    RegisterSpawnHandler(NetworkHash128, SpawnDelegate, UnSpawnDelegate)

    This is an advanced spawning function that registers a custom assetId with the UNET spawning system.

    This can be used to register custom spawning methods for an assetId - instead of the usual method of registering spawning methods for a prefab. This should be used when no prefab exists for the spawned objects - such as when they are constructed dynamically at runtime from configuration data.

    Declaration
    public static void RegisterSpawnHandler(NetworkHash128 assetId, SpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler)
    Parameters
    Type Name Description
    NetworkHash128 assetId

    Custom assetId string.

    SpawnDelegate spawnHandler

    A method to use as a custom spawnhandler on clients.

    UnSpawnDelegate unspawnHandler

    A method to use as a custom un-spawnhandler on clients.

    RemovePlayer(Int16)

    Removes the specified player ID from the game.

    Both the client and the server destroy the player GameObject and remove it from the player list. The playerControllerId is scoped to this client, not global to all players or clients.

    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 static bool RemovePlayer(short playerControllerId)
    Parameters
    Type Name Description
    Int16 playerControllerId

    The local playerControllerId number to be removed.

    Returns
    Type Description
    Boolean

    Returns true if the player was successfully destoyed and removed.

    SendReconnectMessage(MessageBase)

    Send a reconnect message to the new host, used during host migration.

    An example usage might be that if you decide to spawn your own player and not use the built in "Auto Create Player" property in the NetworkManager together with HostMigration, you would need to send a reconnect message when your client reconnects. The code below illustrates such an example were we OnClientConnect check if we where disconnected from the host and in that case we send the reconnect message.

    using UnityEngine;
    using UnityEngine.Networking;
    
    public class NetworkManagerEx : NetworkManager
    {
       public override void OnClientConnect(NetworkConnection conn)
       {
           base.OnClientConnect(conn);
           if (migrationManager.disconnectedFromHost)
           {
               ClientScene.SendReconnectMessage(null);
           }
       }
    }
    Declaration
    public static bool SendReconnectMessage(MessageBase extraMessage)
    Parameters
    Type Name Description
    MessageBase extraMessage

    Any extra data to send.

    Returns
    Type Description
    Boolean

    Returns true if the send succeeded.

    SetLocalObject(NetworkInstanceId, GameObject)

    NetId is a unique number assigned to all objects with NetworkIdentity components in a game.

    This number is the same on the server and all connected clients for a particular object, so it can be used to identify objects across the network. The FindLocalObject() function is called on a client to transform a netId received from a server to a local game object.

    Declaration
    public static void SetLocalObject(NetworkInstanceId netId, GameObject obj)
    Parameters
    Type Name Description
    NetworkInstanceId netId

    NetId of object.

    GameObject obj

    Networked object.

    SetReconnectId(Int32, PeerInfoMessage[])

    Sets the Id that the ClientScene will use when reconnecting to a new host after host migration.

    Declaration
    public static void SetReconnectId(int newReconnectId, PeerInfoMessage[] peers)
    Parameters
    Type Name Description
    Int32 newReconnectId

    The Id to use when reconnecting to a game.

    PeerInfoMessage[] peers

    The set of known peers in the game. This may be null.

    UnregisterPrefab(GameObject)

    Removes a registered spawn prefab that was setup with ClientScene.RegisterPrefab.

    Declaration
    public static void UnregisterPrefab(GameObject prefab)
    Parameters
    Type Name Description
    GameObject prefab

    The prefab to be removed from registration.

    UnregisterSpawnHandler(NetworkHash128)

    Removes a registered spawn handler function that was registered with ClientScene.RegisterHandler().

    Declaration
    public static void UnregisterSpawnHandler(NetworkHash128 assetId)
    Parameters
    Type Name Description
    NetworkHash128 assetId

    The assetId for the handler to be removed for.

    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