Search Unity

2 Camera Moving the exact same but with offset

Discussion in 'Getting Started' started by Hermonicz, Jun 20, 2021.

  1. Hermonicz

    Hermonicz

    Joined:
    Jan 9, 2020
    Posts:
    1
    The idea is that I have a 2 ThirdPersonCameras and they follow my player.
    On the press of a Button the camera over the right shoulder should switch to the camera over the left shoulder.

    SampleScene hierarchy
    • Main Camera
    • Directional Light
    • ThirdPersonPlayer
      • Player
        • Body
        • Follow Target Right
        • Follow Target Left
    • ThirdPersonCameraRight
    • ThirdPersonCaeraLeft


    The Right Camera follows the right and the left camera the left.


    Code (CSharp):
    1. public class ThirdPersonCameraSwitch : MonoBehaviour
    2. {
    3.     public GameObject rightCam;
    4.     public GameObject leftCam;
    5.  
    6.     public bool rightIsActive;
    7.  
    8.     Vector3 offset = new Vector3(0,0,1.0f);
    9.  
    10.     // Start is called before the first frame update
    11.     void Start()
    12.     {
    13.        
    14.     }
    15.  
    16.     // Update is called once per frame
    17.     void Update()
    18.     {
    19.         rightIsActive = rightCam.activeInHierarchy;
    20.         Debug.Log("Right Kamera" + rightCam.transform.position);
    21.         Debug.Log("left Kamera" + leftCam.transform.position);
    22.         if(Input.GetKeyDown("y")){
    23.             if(rightCam.activeInHierarchy){
    24.                 rightCam.SetActive(false);
    25.                 leftCam.SetActive(true);
    26.             }else{
    27.                 leftCam.transform.SetPositionAndRotation(rightCam.transform.position + offset,rightCam.transform.rotation);
    28.                 rightCam.SetActive(true);
    29.                 leftCam.SetActive(false);
    30.             }
    31.         }
    32.     }
    33. }
    This doesnt work. The camera left stays at the Position and Rotation prioer to switching to the other camera.
    They should be always beside each other.

    The Cameras are Cinemachines Free Look cameras.
     

    Attached Files:

  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    OK, in case it wasn't clear, the reason the left camera doesn't move when it's not active is because an inactive object doesn't run any scripts attached to it — including the script that makes it follow the target.

    My recommendation would be: don't have three cameras. Have one camera that can follow any of three positions. And you can do that by simply moving it under the target in the hierarchy (by using Transform.SetParent). This will be much simpler to manage in the long run, than having three cameras which are identical except for where they are.
     
    UnityMaru likes this.
  3. Gregoryl

    Gregoryl

    Unity Technologies

    Joined:
    Dec 22, 2016
    Posts:
    7,711