2017-02-22 137 views
0

我使用生存射擊遊戲資產創建了一個遊戲。我面臨的問題是,攝像機只跟隨主機設備中的主機玩家,而其他客戶端沒有任何玩家跟隨設備。Unity多人遊戲:僅限攝像機跟隨一名玩家

相機按照

public class CameraFollow : MonoBehaviour 
{ 

    Transform target;   // The position that that camera will be following. 
    public float smoothing = 5f;  // The speed with which the camera will be following. 

    Vector3 offset;      // The initial offset from the target. 

    void Start() 
    { 
     target = GameObject.FindGameObjectWithTag ("Player").transform; 
     offset = transform.position - target.position; 
    } 

    void FixedUpdate() 
    { 

     // Create a postion the camera is aiming for based on the offset from the target. 
     Vector3 targetCamPos = target.position + offset; 

     // Smoothly interpolate between the camera's current position and it's target position. 
     transform.position = Vector3.Lerp (transform.position, targetCamPos, smoothing * Time.deltaTime); 
    } 

} 

LocalPlayerSetup腳本

public class LocalPlayerSetup : NetworkBehaviour 
{ 

    void Start() 
    { 
    GameObject.FindGameObjectWithTag ("EnemyManager").SetActiveRecursively (true); 

    if (isLocalPlayer) { 
     GameObject.FindGameObjectWithTag ("MainCamera").GetComponent<CameraFollow>().enabled = true; 
     GetComponent<PlayerMovement>().enabled = true; 
     GetComponentInChildren<PlayerShooting>().enabled = true; 
    } 

} 
+0

'FindGameObjectWithTag'可能不表現良好,當有多個對象共享該標籤。我建議你找一些其他方式來關聯相機和播放器對象。 – rutter

回答

1

不分配目標的相機在其Start方法。相反,使公衆和本土球員的這樣的啓動方法爲它分配:

if (isLocalPlayer) { 
    ("MainCamera").GetComponent<CameraFollow>().target = transform; 
} 
+0

給出錯誤** UnassignedReferenceException:CameraFollow的變量目標尚未分配。 您可能需要在檢查器中指定CameraFollow腳本的目標變量。** –

+0

我已經重點刪除了().enabled = true;這是造成錯誤的原因。感謝您的幫助 –