Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question How to rotate 3rd person Cinemachine camera using script

Discussion in 'Cinemachine' started by Malkata, Feb 9, 2023.

  1. Malkata

    Malkata

    Joined:
    Mar 16, 2021
    Posts:
    5
    My goal is to rotate the camera to a specific direction upon loading scene.

    Let's say the player character goes through a door and enters a new scene. I have made it so that the character would spawn at an empty object using its coordinates for location, but I cannot also use the rotation to set the camera to look away from the door. Cinemachine camera always centers towards the Z axis upon loading new scene.
    The camera is set to follow and look at player character. Rotating the character does not rotate camera. I cannot simply rotate the camera, because as 3rd person camera it orbits around the player - different rotation means different position too.
    I have found that the virtual camera object has a POV Aim/Horizontal Axis/Value parameter which seems to be the exact value I need to set. Is there a way to set in in a script?

    So far I've been trying this to set aim same as empty object rotation:
    cinemachineVirtualCamera.GetCinemachineComponent<CinemachinePOV>().m_HorizontalAxis.Value = gameObject.transform.eulerAngles.y;

    but I get a null ref error.
     
  2. Gregoryl

    Gregoryl

    Unity Technologies

    Joined:
    Dec 22, 2016
    Posts:
    7,267
    cinemachineVirtualCamera.GetCinemachineComponent<CinemachinePOV>().m_HorizontalAxis.Value
    is the correct approach. You need to find out what is null. Add some Debug.Log statements or use a debugger with a breakpoint.

    Another option could be to use vcam.ForceCameraPosition() to directly place it where you want it.
     
  3. Malkata

    Malkata

    Joined:
    Mar 16, 2021
    Posts:
    5
    Thank you for a reply.

    After some dubugging I found my own mistake.
    NullReferenceException actually happens on an earlier line:
    cinemachineVirtualCamera = vcam.GetComponent<CinemachineVirtualCamera>();

    I thought getting the virtual camera component was not working, because it was turning up as null. Turns out I simply forgot to assign the game object to the spawn point at one side of the door, but not the other.
    The method I tried to set rotation works fine now.
     
    Gregoryl likes this.