How do i change cinemachine follow transform in script? (838448)

How can i? Can u send me example script?

vcam.Follow = myNewTarget

I’ll try as soon, thanks.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using EZCameraShake;
using Cinemachine;

public class SwitchCharacter : MonoBehaviour
{

    public GameObject Player, Ship, CameraHandler;

    private CinemachineVirtualCamera vcam;

    void Start()
    {
        vcam = GetComponent<CinemachineVirtualCamera>();

        Player.gameObject.SetActive(true);
        Ship.gameObject.SetActive(false);
    }
    void OnTriggerEnter2D(Collider2D coll)
    {
        if (coll.gameObject.CompareTag("TransformPortalForPlayer"))
        {
            Ship.transform.localPosition = Player.transform.localPosition;
            vcam.Follow = Ship.transform;
            //CameraHandler.GetComponent<CameraMovement>().trg = Ship.transform;
            Player.gameObject.SetActive(false);
            Ship.gameObject.SetActive(true);
            Destroy(coll.gameObject);
            CameraShaker.Instance.ShakeOnce(5f, 5f, .1f, 1f);
        }
        else if (coll.gameObject.CompareTag("TransformPortalForShip"))
        {
            Player.transform.localPosition = Ship.transform.localPosition;
            vcam.Follow = Player.transform;
            //CameraHandler.GetComponent<CameraMovement>().trg = Player.transform;
            Ship.gameObject.SetActive(false);
            Player.gameObject.SetActive(true);
            Destroy(coll.gameObject);
            CameraShaker.Instance.ShakeOnce(5f, 5f, .1f, 1f);
        }
    }
}

NullReferenceException: Object reference not set to an instance of an object
SwitchCharacter.OnTriggerEnter2D (UnityEngine.Collider2D coll) (at Assets/Scripts/SwitchCharacter.cs:27)

I get this error, why? Thanks again.

this line

vcam = GetComponent<CinemachineVirtualCamera>();

is assuming that this script is attached to the vcam. Is it?

Oh, no. I’ll write again and make a return

it worked, thank you

1 Like