Narrowing scope of checks
I'd like to reduce amount of some checks based on the distance to player. Since the distance between two points way less complicated, first I check the distance and then do more complicated stuff (like raycasting). Is it worth? What's the best approach? May be Unity does checks in speed of light?
Answer by NoseKills · Apr 02, 2016 at 10:33 AM
Don't worry about it prematurely. If you loop through your objects and do raycasts, it should be pretty easy to later add a distance check into the "if" before the raycast if you run into performance problems. You can use the profiler to see if it helps or not.
As a general rule though, never use absolute distance to check things unless you really need to know the exact distance... Vector3/2. Distance(a, b) and Vector3.magnitude use Pythagoras theorem to get the result, and it contains a slow-ish square root operation that you probably want to avoid.
If you just want to know if something is in/out of range, you only need to compare distances, you don't need to know the exact distances so you can avoid the square root and compare the squared values:
Vector3 a = Vector3.zero;
Vector3 b = Vector3.one;
Vector3 fromTo = b - a;
const float range = 5;
if (fromTo.magnitude < range ) // slower
if (Vector3.Distance(a, b) < range ) // slower
const float rangeSquared = 5*5;
if (fromTo.sqrMagnitude < rangeSquared) // faster
I'm also thinking of using box collider trigger of certain size to add or remove object dynamically to/from the scope. What can you say about this idea?
Adding more colliders certainly won't make the engine perform faster unless you somehow had a situation where your raycasts (without filtering) make for over 50% of the performance hit in the game.
The physics engines in Unity are pretty damn mature and optimized so don't spend time thinking about complex ways to optimize things before you know you have a performance problem.
Your answer
Follow this Question
Related Questions
Unity3d Under the hood 0 Answers
Simple POP UP Damage Script-Animation 0 Answers
Is calling OnCollisionEnter2D on allot of GameObjects leading to worse performance? 0 Answers
TransformChangeDispatch for UI 0 Answers
IEnumerator Tweening vs Animator - Which is the better performance choice? 0 Answers