Home / Forums / Unity ESP Performance Optimization: Caching, Garbage Collection & Spatial Partitioning

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Discussion

Unity ESP Performance Optimization: Caching, Garbage Collection & Spatial Partitioning

RustMechanic
Unity & IL2CPP Reverser
VIP
Rep: 295
Join Date: Nov 2022
Posts: 32
Thanks: 74
1y ago · Feb 18, 2025 3:10 PM
#1
When writing internal or BepInEx mods for Unity games with high entity counts (100+ players/zombies/items), improper code in
CODE
OnGUI
or
CODE
Update
will cause noticeable micro-stutters.

Top 4 Rules for Zero-Lag Unity ESPs:

1. Never call
CODE
Camera.main
every frame:

In older Unity versions,
CODE
Camera.main
performs an expensive
CODE
GameObject.FindWithTag("MainCamera")
under the hood. Cache it in a field on
CODE
Update()
or
CODE
Start()
.

2. Avoid LINQ and foreach closures in OnGUI:
CSHARP
// BAD: Allocates IEnumerator on heap every frame (GC spikes)
foreach (var p in playerList.Where(x => x.isAlive))

// GOOD: Zero-allocation for-loop with indexed list
for (int i = 0; i < cachedPlayers.Count; i++) {
    var p = cachedPlayers[i];
    if (!p.isAlive) continue;
}


3. Pre-allocate GUIStyles and GUIContent:
Creating new
CODE
new GUIStyle()
or
CODE
new GUIContent()
inside
CODE
OnGUI()
generates megabytes of garbage memory per second. Always make them
CODE
static readonly
!

4. Spatial Distance Culling:
Skip WorldToScreen calculations for entities beyond your configured render distance:
CSHARP
if ((targetPos - localPos).sqrMagnitude > maxDistSqr) continue;

(
CODE
sqrMagnitude
skips expensive
CODE
sqrt
operations).
RustMechanic | IL2CPP & Unity Engine Analysis
The following users thanked RustMechanic for this post:
IL2Cpp_Wizard
IL2Cpp & Metadata Engineer
VIP
Rep: 360
Join Date: Feb 2023
Posts: 21
Thanks: 92
1y ago · Feb 18, 2025 5:35 PM
#2
CODE
sqrMagnitude
optimization is huge. Also in IL2CPP, passing structs by
CODE
in
or
CODE
ref
prevents copying 12-byte Vector3 values across native bridge boundaries.
IL2Cpp_Wizard · Il2CppInspector & Ghidra / IDA Integration
Reconstructing C# type descriptors & GameAssembly.dll offsets
HexRays99
Senior Reverse Engineer
VIP
Rep: 380
Join Date: Apr 2022
Posts: 36
Thanks: 94
1y ago · Feb 19, 2025 10:12 AM
#3
These 4 optimization rules should be standard reading for every Unity mod developer. Eliminating GC allocations ensures solid 144+ FPS in-game!
HexRays99 · Reverse Engineering & Static Analysis
CPP
// Always check your pointers!
if (!pLocalPlayer) return;