What if my Billboarding toward the cameria is Better :P

I actually thought about not putting this cause like it actually matters less if you are in unity 2020 or newer, but since the course is written in unity 2018…

Searching for the camera in update is supposedly kind of expensive. I’m sure he will make this better later in the course, but for now at least I’m caching a reference to the camera just for a bit of optimization.

@Brian_Trotter is the above correct? if so, does the caching help? I don’t actually know why its a problem i just remember reading it was in a forum or on a tutorial a while ago. my assumption is that its just generally resource intensive to look for camera components but its just a guess.

using UnityEngine;

namespace RPG.Core
{
    public class CameraFacing : MonoBehaviour
    {
        Camera _camera;

        private void Awake()
        {
            _camera = Camera.main;
        }

             void Update()
        {
            transform.forward = _camera.transform.forward;
        }
    }

Caching definitely helps here, regardless of Unity version.

Camera.main, under the hood is equivalent to

public Camera main
{
    get
    {
          return GameObject.FindWithTag("MainCamera").GetComponent<Camera>();
    }
}

In a small scene, this is actually negligible, but in an Update() loop, the more GameObjects in your scene, the longer this search can take. Cachine here is definitely recommended, even with Cinemachine active.

There are many similar optimizations that can be made within the course. As a rule, any component that exists on the same GameObject as the component can be cached. Components on other GameObjects (for instance on a target) should generally not be cached unless you need to access them in every Update() cycle.

Sam and Rick’s philosophy regarding caching is that this is an optimization to be made once you’ve settled on a specific implementation. Think of it as a final refactor to shore things up. To quote Rick “First make sure it works, then tidy it up”

One of the tutorials in my //TODO: list is to cover these sorts of tidy up optimizatons,

2 Likes

thanks Brian, you are helpful as ever :slight_smile:

Privacy & Terms