Consider using distance-squared over distance

It is safe to say that CPUs are relatively good at multiplying floating-point numbers together, but relatively dreadful at calculating square roots from them. Every time we ask a Vector3 to calculate a distance with the magnitude property or with the Distance() method, we're asking it to perform a square root calculation (as per the Pythagorean theorem), which can cost a lot of CPU overhead compared to many other types of vector math calculations.

However, the Vector3 class also offers a sqrMagnitude property, which is the same as distance, only squared. This lets us perform essentially the same comparison check without the expensive square root included, so long as we also square the value we're trying ...

Get Unity 5 Game Optimization now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.