Normally I wouldn’t be this pedantic but I’m very conscious of performance optimization within Update() and Update alone.
In this lecture we check for isInRange in Update() before a target is even identified as not being null. Wouldn’t it be more efficient to first check whether a target exists before performing the calculations?
My code is:
if (target != null)
{
bool isInRange = Vector3.Distance(transform.position, target.position) < weaponRange;
if (isInRange)
{
GetComponent<Mover>().MoveTo(target.position);
}
else
{
GetComponent<Mover>().Stop();
}
}
I did some more research on this concept generally within the Unity community and find a kind of “blase” approach to Update, as if no one really worries about optimizing it. The reason normally given is that “you’re bound to run into other optimization problems before Update”. I thought this a good opportunity to ask two additional questions if anyone has the time -
-
Is the reason that we check isInrange before even checking if a target is not null so that we can keep the FPS consistent? I know this is a trivial example and would make no difference to FPS, but is it advisable to do it the way described in the lecture as opposed to the way I propose purely so that we don’t run into any “FPS gotchas”. For instance if isInrange was very, very expensive (which of course it’s not here, I just mean hypothetically) it might be very difficult to otherwise pinpoint why the FPS drops when we attack a target as opposed to when we don’t? If we do it the lecture way this would be easy to identify since the FPS would be more consistent everywhere; if we do it my way it would be hard to track. Is this the reason it’s done the way it is in the lecture, so we can ensure a consistent FPS at all times everywhere by even making unnecessary Update calls, or am I overthinking things?
-
Why does the Unity community seem to have this general ‘blase’ approach to Update() calls? Coming from Phaser I found the limiting factor in FPS for games to be Update() calls, and I’m also thinking of creating 2D games in Unity as well where there might be many thousands of cheap texture sprites but each with comprehensive and costly Update() AI logic. Being blase about Update in Phaser certainly didn’t help me, it became the sole and main focus of optimization especially for “cheap to render” game objects. Should Update optimization in Unity be taken seriously or is it true that there will always be other limiting factors before it becomes an issue unlike in other frameworks such as Phaser? Is this answer still the same considering cheap 2D sprites for a 2D project where each sprite might make complicated Update() calls?
I realize this is a lot to ask but I’m thinking perhaps the answers would assist many future students wondering similar things in addition to myself. Thank you very much for the time if you’re able to answer as this would clear a lot of things in mind about optimization intuition coming from Phaser.