Legacy Documentation: Version 2018.1 (Go to current version)
LanguageEnglish
  • C#
  • JS

Script language

Select your preferred scripting language. All code snippets will be displayed in this language.

NetworkServer.AddPlayerForConnection

Suggest a change

Success!

Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.

Close

Submission failed

For some reason your suggested change could not be submitted. Please <a>try again</a> in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.

Close

Cancel

public static method AddPlayerForConnection(conn: Networking.NetworkConnection, player: GameObject, playerControllerId: short): bool;
public static bool AddPlayerForConnection(Networking.NetworkConnection conn, GameObject player, short playerControllerId);

Parameters

connConnection which is adding the player.
playerPlayer object spawned for the player.
playerControllerIdThe player controller ID number as specified by client.

Returns

bool True if player was added.

Description

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.

#pragma strict
class MyServer extends MonoBehaviour {
    public var playerPrefab: GameObject;
    function Start() {
        NetworkServer.RegisterHandler(MsgType.AddPlayer, OnAddPlayerMessage);
    }
    function OnAddPlayerMessage(netMsg: NetworkMessage) {
        var thePlayer: GameObject = GameObjectInstantiate(playerPrefab, Vector3.zero, Quaternion.identity);
        // This spawns the new player on all clients
        NetworkServer.AddPlayerForConnection(conn, thePlayer, 0);
    }
}
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); } }

Did you find this page useful? Please give it a rating: