Code Optimization For Camera Switching

hi everyone! I am new to C# and Unity and would like to ask different ways on writing this code:

 public GameObject player;
    public Vector3 offset1st = new Vector3(0, 5, -7);
    public Vector3 offset3rd = new Vector3(0, 0, -7);
    private bool CamSwitch; 

    void Start()
    {
        player = GameObject.Find("Vehicle");
      
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space)) {
            CamSwitch = !CamSwitch;
        }

    }
    void LateUpdate()
    {

        if (CamSwitch)
        {
            transform.position = player.transform.position + offset3rd;
        }
        else if (!CamSwitch)
        {
            transform.position = player.transform.position + offset1st;
        }

        
    }

I successfully made this simple code working toggling between Camera’s first and third person view on a driving game. Just wondering if there are better ways to write this.

Looking forward to discuss with you all!

Well there are few issues with it. The most noticeable is that LateUpdate will execute one of two position changes even when nothing has changed. You probably need a private bool to represent it’s current position.

I can’t actually tell but it appears that having possibly set the player object (it’s public BTW) you actually want the Vehicle game object. If you can assign that rather than Find it you would be slightly better off.

And the formulas you have in LateUpdate are “identical” save the offset used. That can easily be a single line with a ternary operator to determine which offset to use.

2 Likes

You really should use Cinemachine. Yes I get that’s just two cams you’re exclusively enabling, but still, Cinemachine baby.

ALSO: this is a huge no-no, as tley hints at above:

Remember the first rule of GameObject.Find():

Do not use GameObject.Find();

More information: Regarding GameObject.Find ¡ UnityTipsRedux

In general, DO NOT use Find-like or GetComponent/AddComponent-like methods unless there truly is no other way, eg, dynamic runtime discovery of arbitrary objects. These mechanisms are for extremely-advanced use ONLY.

If something is built into your scene or prefab, make a script and drag the reference(s) in. That will let you experience the highest rate of The Unity Way™ success of accessing things in your game.

“Stop playing ‘Where’s GameWaldo’ and drag it in already!”

Here’s why all this stuff is CRAZY code:

1 Like

you are indeed correct. I privated the offsets and it works better. I am going to try rewriting it with ternary operation.

Thank you