Search Unity

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

Discussion in 'Scripting' started by Infinite_ride, Dec 9, 2022.

  1. Infinite_ride

    Infinite_ride

    Joined:
    Dec 3, 2022
    Posts:
    3
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class FollowCar : MonoBehaviour
    4. {
    5.     //set variables
    6.     public GameObject car;
    7.     private Vector3 thirdOffset = new Vector3(0,5,-7);
    8.     private Vector3 firstOffset = new Vector3(0,3,0);
    9.     public bool Onthird = true;
    10.  
    11.     void LateUpdate()
    12.     {
    13.         if (Onthird == true) //if third person is enabled do:...
    14.         {
    15.            transform.position = car.transform.position + thirdOffset;
    16.            //sets camera behind the car
    17.            transform.eulerAngles = new Vector3 (20,0,0);
    18.             //rotates camera a little bit down
    19.         }
    20.         else  //if first person is enabled do:...
    21.         {
    22.             transform.position = car.transform.position + firstOffset;
    23.             //makes cam follow car
    24.             transform.eulerAngles = car.transform.eulerAngles;
    25.             //makes cam follow car rotation
    26.         }
    27.         if (Input.GetKeyDown("space"))  //checks if space is pressed
    28.         {
    29.             //switches camera variable to opposite
    30.             Onthird = !Onthird;
    31.         }
    32.     }
    33. }
    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...
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,697
    Best way to optimize it is to just delete it all and use Cinemachine. :)

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

    There's even a dedicated forum: https://forum.unity.com/forums/cinemachine.136/