-
Notifications
You must be signed in to change notification settings - Fork 88
Vector Position Performance Improvements
Vectors and Position/Rotational maths can be costly and especially since you are interacting with the Unity API it can lead to hidden performance issues. This is just a bunch of general tips to help improve performance of your scripts. This is gathered from a variety of sources, from official docs to official talks to my own testing and analysation.
gameobject.position
is expensive, since it actually performs a few safety checks which well in most cases (rather in all cases) you don't need, in this case if you are going to change a position a lot then it is better to cache that position (since it's a class it is passed by reference), which avoids all those checks!
Everything in unity is stored as a local position, so when you ask for a non-local position it has to go through all the parents and collect their local positions to give you a proper global position, this means it has to perform the safety checks described above not only once, but for every single parent, especially in UI systems avoid using any global positions/rotations... (and so on) the UI system is built to be relative (with anchors and so on) so make sure your code reflects that principle if you want to use that power.
This will avoid having to perform the check twice and will perform it in a more efficient manner (note that this function sets the world coordinates not the local coordinates, hopefully Unity will eventually release both their internal GetPositionAndRotation
and their internal local variants!).
Avoid using something like transform.position = new Vector3(X, Y, Z);
and rather do something like;
transform.position.x = X;
transform.position.y = Y;
transform.position.z = Z;
This is down to the fact that Vector3 (and all its variants) are actually structs, structs are stack created (well mostly unless you force them to be heap through some weird concoction of a situation) and so when you perform a line like that it has to move over the vector (though in saying that JIT should cover this and make this more efficient, for some reason it doesn't could be with how transform.position getter is set up), it is severely more efficient to set each of the x/y coords without creating the new object.
However, I hope this goes without saying that the following is less efficient than just setting the property;
void MyMethod(Vector3 pos) {
transform.position.x = pos.x;
transform.position.y = pos.y;
transform.position.z = pos.z;
// Less efficient than just saying;
transform.position = pos; // You already created the object and the overhead of three calls is less efficient than just simply use this.
}
- Features
-
Roadmap
- Milestone 0.3
- Milestone 0.2 (reached)
- Milestone 0.1 (reached)
- Gameplay
- Frequently Asked Questions