Search Unity

Question please help to set up cinemachine.

Discussion in 'Timeline' started by mlbot, Aug 16, 2023.

  1. mlbot

    mlbot

    Joined:
    Mar 13, 2023
    Posts:
    2
    I have a very simple task. A player is created from the prefab on the stage, you need to link it to a virtual camera. When he dies, untie the camera and bind it again after respawn. I honestly spent three weeks trying to watch training videos or sort out the documentation. But it is difficult to find a simple answer to such a seemingly simple question.
    as I understand it, I need a couple of lines of code to get a new object and throw it into the "fallow" and "lookAt" But unfortunately I can't figure out how to prescribe it correctly on my own.
    thank you in advance
     
  2. Gregoryl

    Gregoryl

    Unity Technologies

    Joined:
    Dec 22, 2016
    Posts:
    7,707
    There are several ways to do this. Here are a couple:

    Option 1: Change the prefab to include the virtual camera. In the prefab, create a parent object and give it 2 children: the player, and the virtual camera. Set up the virtual camera in the inspector to follow the player. Then, when you spawn this prefab, you will be simultaneously spawning the player and the camera, already connected.

    Option 2: Dynamically connect the newly-spawned player to an existing vcam (what you asked). Assuming that your script has a pointer to the vcam, do something like this:
    Code (CSharp):
    1.     public CinemachineVirtualCameraBase vcam; // this is the existig virtual camera
    2.     public GameObject PlayerPrefab;
    3.  
    4.     void Spawn(Vector3 position, Quaternion rotation)
    5.     {
    6.         var player = Instantiate(PlayerPrefab, position, rotation);
    7.         vcam.Follow = player.transform;
    8.         vcam.LookAt = player.transform;
    9.         vcam.PreviousStateIsValid = false; // make the vcam snap to the new position
    10.     }
     
    mlbot likes this.
  3. mlbot

    mlbot

    Joined:
    Mar 13, 2023
    Posts:
    2
    Thanks