2016-07-18 66 views
1

我想知道如何在Unity網絡中的可控對象之間來回切換。在Unity Networking中切換播放器對象

例如,假設有兩個對象Player1和Player2,並且您正在控制Player1。按空格鍵,你現在控制着Player2。再按一次,回到控制Player1。

我做了什麼: 我跟着the Unity Manual達人「測試多人運動」,並參照「切換玩家」在Player Objects
我改變了玩家的腳本如下:

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); 
     } 
    } 

} 

而且,Player2對象是通過將Player1(Prefab)拖到層次結構來創建的。

錯誤: 我試過玩它,並且從Player1切換到Player2時,從Player2切換回Player1不會。錯誤消息如下:

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) 

回答

0

對於使用網絡對象,您應該首先分配權限才能使用它。

假設如果你在PLAYER1並希望切換到player2然後,

分配權力player2並從PLAYER1機構(反之亦然另一個開關)。

爲了分配權限,您應該使用這個AssignClientAuthority。對於代碼的實際實現,我會推薦你​​this unity forum discussion(值得理解)。