Unity CPU Optimizations
Use magnitude instead of sqr for distance checking
Vector3 pos1;
Vector3 pos2;
float distance1 = Vector3.Distance(pos1, pos2);
float distance2 = (pos1 - pos2).magnitude; // same result as distance1
// For a distance check this is the fastes way
float distance3 = (pos1 - pos2).sqrMagnitude; // result is distance1 * distance1
Cache transform
Cache transform on awake or start.
using UnityEngine;
public class Example : MonoBehaviour
{
Transform trans = null;
// Start function
void Start()
{
trans = transform;
}
// Update function
void Update()
{
trans.position = new Vector3(0.0f, 0.0f, 0.0f);
}
}
Vector math optimization
Vector3 oldPos; // old position
Vector3 dir; // movement direction
float speed; // movement speed
float input; // input factor
// This is slow
Vector3 pos = oldPos + dir * speed * input * Time.deltaTime;
// This is faster, because only one factor is used
Vector3 pos = oldPos + dir * (speed * input * Time.deltaTime);
// This inlining is the fastes
Vector3 pos = oldPos;
float factor = speed * input * Time.deltaTime;
pos.x += dir.x * factor;
pos.y += dir.y * factor;
pos.z += dir.z * factor;
Cache Time.deltaTime
Cache Time.deltaTime once per frame so you don't have to call into the c++ side of Unity.
Don't move static objects
Don't move Rigedbodies via transform
Use local position and rotation
Inline functions
If before 4.6 runtime manually. After via attribute.
using UnityEngine;
using System.Runtime.CompilerServices;
public class Example : MonoBehaviour
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void Function()
{
}
}
Use string builder
Use shorts and unigned for network communication
Use Unity C# Job System
Reduce generated garbage for the gc
Use subcanvases
Don't use animators for UI
Use a tween system.
Avoid layout groups
If this is not possible use a canvas for this part of the UI.
Use il2cpp instead of mono
Use observer pattern for UI instead of updating it every frame
Don't update every system every frame
Use different tick rates for different systems if possible.
Use instancing
Try to get away with mobile shaderes
Don't use foreach
Don't use linq
Use id version of Animator, Material and Shader functions
Don't use string versions. The id can be cashed at awake or start.
From 5.3 on use non-alloc versions of RaycastAll and Spherecast
Avoid null checks of MonoBehaviour in hotpasse code
Unity goes into c++ side for this operation.
Use the min length and mask for raycasts
Use one dim arrays
float[] best;
float[][] good;
float[,] worst;
Use an UpdateManager instead of the MonoBehavior Update function
Cache Vectors like Vector3.zero and Quatornion.identity
Unity creates a new Vector every time it's practically like new Vector3(0, 0, 0). Use static readonly because Vectors can't be const.
Don't use enums as keys for dictionaries
Cach array that comes from Unity (f. e. mesh.verticies)
Unity creates them new every time you access them.
Avoid slow string API functions
Make your own. This can be up to 10 or even 100 times faster.
Parse json and xml files on worker threads if no Unity type is part of them
Use module for selecting frame you want to wo some stuff
This is usefull for AI and other systems.
using UnityEngine;
public class Example : MonoBehaviour
{
int interval = 3;
void Function()
{
if(Time.frameCount % interval == 0)
{
// Do some stuff every 3rd frame
}
else if (Time.frameCount % interval == 1)
{
// Do some stuff every 3rd frame but on the second frame
}
}
}
Parent GameObjects on instantiate not seperate afterwards
Use structs instead of classes
Structs are created on the stack not on the heap.
Use the compare tag function not ==
Use Set function of a Transform only once per frame per object
Change the physics timestep to the slowest you can get away with
Don't use OnInside callback for a collider
Use layers instead of tags
Combine meshes to reduce draw calls
This can be done with an editor tool.
Bake textures into atlases
The function Texture2D.PackTextures can bake multiple textures into an atlas.
Remove raycaster on non interactable canvases
Disable raycast target on UI.Images if it's not interactable
You can disable nullcheckers and array boundrary checkers in il2cpp
Use the attributis inside the Il2cppSetOptionAttribute.cs file.
Remove animation settings if not needed
This will reduce memory and loading time.
Don't use humanoid animation settings if not needed
Only use humanoid animation settings if you need inverse kinematic or animation retargeting. Use generic instead.