1

I would like to know how I can switch back and forth between controllable objects in Unity's networking.

For example, say there are two objects, Player1 and Player2, and you're controlling Player1. By pressing the spacebar, you're now controlling Player2. Press again, goes back to controlling Player1.

What I have done: I followed the Unity Manual up to "Test Multiplayer Movement", and by referring to "Switching Players" in Player Objects
I changed the Player's script to as follows:

using UnityEngine;
using UnityEngine.Networking;

public class PlayerMove : NetworkBehaviour {

    string player1;
    string player2;

    void Start(){
        player1 = "Player1(Clone)";
        player2 = "Player2";
    }

    // Update is called once per frame
    void Update () {
        if(!isLocalPlayer){
            return;
        }


        float x = Input.GetAxis("Horizontal")*0.1f;
        float z = Input.GetAxis("Vertical")*0.1f;

        transform.Translate(x, 0, z);

        if(Input.GetKeyDown(KeyCode.Space)){
            Debug.Log("switched");
            PlayerChange(this.gameObject);
        }
    }

  public void PlayerChange(GameObject oldPlayer)
  {
      var conn = oldPlayer.GetComponent<NetworkIdentity>().connectionToClient;

      GameObject newPlayer;
      if(this.gameObject.name == player1){
          newPlayer = GameObject.Find(player2);
          NetworkServer.ReplacePlayerForConnection(conn, newPlayer, 0);
      }
      else{
          newPlayer = GameObject.Find(player1); 
          NetworkServer.ReplacePlayerForConnection(conn, newPlayer, 0);
      }  
  }

}

Also, Player2 object is created by dragging Player1 (Prefab) to Hierarchy.

Error: I tried playing it, and while switching to Player2 from Player1 works, switching back to Player1 from Player2 does not. The error message goes:

SetClientOwner m_ClientAuthorityOwner already set!
UnityEngine.Networking.NetworkServer:ReplacePlayerForConnection(NetworkConnection, GameObject, Int16)
PlayerMove:PlayerChange(GameObject) (at Assets/PlayerMove.cs:43)
PlayerMove:Update() (at Assets/PlayerMove.cs:28)

1 Answer 1

0

For using a network object you should need to assign the authority first in order to use it.

Suppose if you are at player1 and want to switch to player2 then,

Assign authority to player2 and remove authority from player1(and vice-versa for another switch).

For assigning authority you should use this AssignClientAuthority. For practicle implemntation of the code i'll recommend you this unity forum discussion(worth to understand).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.