- Home /
When does Unity calculate vectors' magnitudes?
Hi.
For obvious reasons, I can't get full details about how certain classes and structs provided by Unity work. I only can see public members from metadata.
So my question is about Vector2 and Vector3 structures. The most logical way to get magnitude is to store it in a public property with a private set accessor and only recalculate it when a new vector is created or when one of vector's components changes.
However, Unity documantation here says it's preffered to use sqrMagnitude instead of magnitude in some cases. As if to improve performance, they are only calculated when called. This makes me think these properties realized in this way:
public float magnitude => Mathf.Sqrt(x * x + y * y + z * z);
public float sqrMagnitude => x * x + y * y + z * z;
So how do these properties actually work?
Answer by Serega4567 · Oct 18, 2021 at 07:57 AM
Ok, when I posted this topic, I already understood that my guesses are most likely correct and I will not wait for an answer from anyone. Indeed, in some mathematical software it would probably make sense to calculate the magnitude of a vector every time, but not in a game engine, where a great deal of this structures is created every second.
After a little magic in JetBrains dotPeek, I found a confirmation of my thoughts:
public float magnitude => (float) Math.Sqrt((double) this.x * (double) this.x + (double) this.y * (double) this.y + (double) this.z * (double) this.z);
public float sqrMagnitude => (float) ((double) this.x * (double) this.x + (double) this.y * (double) this.y + (double) this.z * (double) this.z);
As you said, there's no need for guessing in those cases for two reasons. First of all, as you have already figured out, you can decompile the UnityEngine.dll with any .NET reflector (I perfer ILSpy). Secondly Unity provides the full source code of the managed part of the engine for reference only on their github account..
Make sure you read the license before copying anything from this repository. It's just provided for reference.
Anyways here is how magnitude and sqrMagnitude are defined. Note that some methods are actually defined on the C++ side, usually for performance reasons. Here is the part of the Vector3 struct that is defined in native code. Whenever you see an "extern" definition, the actual code lives in the native code (that is closed source).
Your answer
Follow this Question
Related Questions
force.normalized * magnitude 1 Answer
Player slows down every time they are movies? 0 Answers
Replace Quaternion with Vector2 in Quaternion times Vector3 equation? 1 Answer
One script for all variables? 0 Answers
Closest point on multiple lines? 2 Answers