Switch camera positions from input

Hello, I’m attempting to have the camera of the player switch to the vehicle (tank) when pressing E.

The Main Camera object has the camera follow script

public class CameraFollow : MonoBehaviour
{
    [SerializeField] Transform player;
    [SerializeField] Vector3 offset;
    private float smoothSpeed = 0.125f;

    void FixedUpdate()
    {
        //lowercase transform refers to current object

        Vector3 originalCameraPosition = player.position + offset;

        //Lerp - linear interpolation (one point to another)
        //Vector3.Lerp(position1, postion2, value);
        Vector3 smoothCameraPosition = Vector3.Lerp(transform.position, originalCameraPosition, smoothSpeed);

        transform.position = smoothCameraPosition;
        transform.LookAt(player);
    }
}

I also have a vehicle class: I’ve attempted to have refer to the CameraFollow class within Vehicle and the OnCollisionEnter (upon input) will switch camera positions.

public class Turret : MonoBehaviour 
{
    // This is just a snippet of the code, I removed irrelevant code
    private CameraFollow cameraReferece;

	void Update () {

	}

    void OnCollisionEnter(Collision c)
    {
        if (c.collider.gameObject.tag == "Player" && Input.GetKey("e"))
        {
            cameraReferece = new CameraFollow();
            //cameraReferece.player = this.cameraReferece;
            CheckInput();
        }
    }

Thanks.

First, why OnCollision? With that the player would have to be holding E when he first collides with the tank.

As far as the camera, you are not reaching the camera gameObject with your turret script - you only create a new instance of the CameraFollow script. There’s a number of different ways to actually reference the CameraFollow script that’s on your camera gameobject:

  • Make the CameraFollow script static so any reference to CameraFollow will reach the original (a bit risky but it works).
  • Put a serialize field in front of your cameraReference variable [Serialize Field] private CameraFollow cameraReferece; Then you can drag the camera with the CameraFollow script onto that field in the inspector (can be a bit tedious depending on how many turrets you have).

But in a perfect world your camera would just have different states that were triggered by your interactions and you wouldn’t need to put camera code on different game objects.