Noob here... How would I optimize this line of code to not run every frame?

using UnityEngine;

public class FollowCar : MonoBehaviour
{
    //set variables
    public GameObject car;
    private Vector3 thirdOffset = new Vector3(0,5,-7);
    private Vector3 firstOffset = new Vector3(0,3,0);
    public bool Onthird = true;

    void LateUpdate()
    {
        if (Onthird == true) //if third person is enabled do:...
        {
           transform.position = car.transform.position + thirdOffset;
           //sets camera behind the car
           transform.eulerAngles = new Vector3 (20,0,0);
            //rotates camera a little bit down
        }
        else  //if first person is enabled do:...
        {
            transform.position = car.transform.position + firstOffset;
            //makes cam follow car
            transform.eulerAngles = car.transform.eulerAngles;
            //makes cam follow car rotation
        }
        if (Input.GetKeyDown("space"))  //checks if space is pressed
        {
            //switches camera variable to opposite
            Onthird = !Onthird;
        }
    }
}

Hi, I believe that the camera being set to a fixed rotation every frame (line 17) while on third person can be optimized to be called only while switching to first person, but im too noob to know how. Any ideas?

EDIT: I guess I could “nest if statements” but I heard is bad practice or something…

Best way to optimize it is to just delete it all and use Cinemachine. :slight_smile:

Camera stuff is pretty tricky… you may wish to consider using Cinemachine from the Unity Package Manager.

There’s even a dedicated forum: Unity Engine - Unity Discussions