Alternate Solution to NavMeshAgent mover and question about caching

I grabbed the nav mesh agent in Awake and then moved it in update. Just curios which way is is more efficient or resource protective… On one side i know some of the tutorials talk about not caching things all the time, on the other side i know you want to minimize what you can in the update callback since its every frame. Also if im caching the agent is it better to do in start or awake?

{
    [SerializeField] Transform _targetTransform;
    private NavMeshAgent _agent;

    private void Awake()
    {
        _agent = GetComponent<NavMeshAgent>();
    }

    private void Update()
    {
        _agent.destination = _targetTransform.position;
    }
}

For components, it’s generally best to cache those references in Awake(). It’s also generally better to cache the references than to constanly call for them in Update().

1 Like

thanks Brian, i know I’m always bothering with tedious “efficiency/optimization” questions. I come from a background in global systems engineering. I have been burned a thousand times by developers with memory leaks and stuff like that, so I’m probably approaching this kind of stuff with an excess of caution(especially since I’m targeting mobile platforms for my first actual game release).
Happy new year :slight_smile:

I have over 40 years of coding experience. I share your excess abundance of caution. I null check things that logic would say cannot possibly be null, I cache references to save clock cycles when I can, and avoid caching them when the reference is more dynamic.

When the course was written, Sam and Rick’s philosophy was focused on teaching you the “what”, as in this is how you do this thing. In the prototyping phase, we often don’t worry about caching variables and such, especially because we may refactor the whole thing and have to do something with those cached references. Once you get through the prototyping phase, that’s when it’s time to cache references, turn that Heads Up display from an Update Loop to an observer pattern, and do whatever else you can think of to squeeze those clock cycles, because the more code you’re running in the Update Loop, the slower your frame rate will be.

In short, keep those optimization questions coming. :slight_smile:

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms