Unity’s AI Toolkit can save you time, but it also introduces new ways to leak memory if you are not careful with how you create, reuse, and destroy:
- AI agents
- Brains/behaviours
- ScriptableObject data
- Observations, decisions, and logs
Symptoms usually show up as:
- Editor or build using more and more RAM the longer you play
- Mobile builds that slow down or crash after several matches
- Profiler showing constantly rising Managed Heap or Gfx/Native memory
This guide focuses on practical, engine‑level fixes—even if you treat the AI Toolkit as a black box.
1. Confirm It’s Really a Memory Leak (Not Just a Heavy Scene)
Before you blame AI Toolkit, verify that memory is actually growing without bound.
1.1. Use the Unity Profiler
- Open
Window → Analysis → Profiler. - In the Memory module, watch:
- Total Allocated and Reserved memory
- Managed Heap size
- Run your game for several minutes:
- Move through typical gameplay.
- Let AI agents spawn, think, and despawn if applicable.
You are looking for:
- A clear upward trend that never stabilizes—even when you:
- Return to menus
- Finish sessions
- Disable unrelated systems
If memory spikes but then falls and plateaus:
- You likely have heavy but bounded allocations, not a leak.
- You can still optimize, but it is a different problem.
2. Check AI Agent and Brain Lifetimes
The single biggest risk with AI Toolkit is creating agents/brains that never truly die.
Common patterns that cause leaks:
- Instantiating new agent GameObjects every round without destroying old ones
- Keeping references to agents or brains in static fields or singletons
- Spawning “helper” objects per agent that are never cleaned up
2.1. Audit your agent prefabs and spawners
For each AI‑controlled character:
- Confirm that:
- Agents are spawned via a central spawner or known systems.
- There is a clear path to Destroy or disable them when:
- The match ends
- The scene changes
- The enemy/NPC is supposed to be gone
When agents are destroyed:
- Any components and references attached to them (including AI Toolkit behaviours) should be eligible for garbage collection.
2.2. Avoid static references to agents and brains
Look for code like:
public static List<AIToolkitAgent> AllAgents = new();
If you add agents and never remove them:
- Their memory cannot be reclaimed.
Safer approach:
- Use a scene‑bound manager (
MonoBehaviourin the scene) instead of static fields. - Ensure you remove entries on agent destruction (e.g., in
OnDestroy).
3. Watch Out for Unbounded Data Structures (Logs, Observations, Histories)
AI‑driven systems often store:
- Past observations
- Debug logs per decision
- Replay data
If these grow forever, you leak memory even if your agent objects do not.
3.1. Audit lists and dictionaries in AI‑related scripts
Search your AI Toolkit wrappers and helpers for:
List<>,Dictionary<>, or similar collections used to:- Track decisions or events over time
- Cache behaviour outputs
For each:
- Make sure you:
- Clear the collection when it is no longer needed (e.g., at end of round).
- Or cap its size (e.g., keep only the last N items).
3.2. Disable or throttle verbose logging in production
If AI Toolkit or your glue code writes large logs:
- Disable debug logging for builds (especially mobile/consoles).
- Avoid storing logs in memory for the entire session.
Use conditional compilation (#if UNITY_EDITOR, etc.) to keep heavy debug utilities out of release builds.
4. Profile AI Toolkit Allocations Narrowly
To be sure AI Toolkit is involved:
- In the Profiler, filter to:
- CPU → Timeline and Memory.
- Run the game without AI:
- Temporarily disable spawners or brain components.
- Run the game with AI enabled:
- Same scene, same duration.
Compare:
- Does memory grow only when AI Toolkit is active?
- Are there particular frames or actions where allocations spike?
You can also:
- Take Memory snapshots (Profiler or Memory Profiler package) at:
- Start of match
- Mid‑match
- After several matches
Look for:
- AI Toolkit types and your AI wrapper scripts in the diff between snapshots.
5. Use Scene Unloads and Cleanup Hooks Deliberately
If your game uses additive scenes or reloads the same scene frequently, you must ensure:
- AI systems unsubscribe from events
- Nothing keeps references to dead scenes
5.1. Unsubscribe from events in OnDisable/OnDestroy
Whenever AI Toolkit hooks into events (UnityEvents, C# events, or custom signals), make sure you:
- Subscribe in
OnEnableor initialization. - Unsubscribe in
OnDisableorOnDestroy.
Otherwise, memory can be held by:
- Event publishers that remain alive across scenes
- Long‑lived managers holding onto handlers
5.2. Test scene reload behaviour explicitly
Create a minimal test:
- Scene A:
- Spawns a few AI agents.
- Scene B:
- Empty.
Loop:
- Load Scene A → run AI → load Scene B → repeat several times.
Watch memory:
- It should return near the initial level each loop.
- If it increases every cycle, examine which objects survive scene unloads.
6. Update to the Latest Compatible AI Toolkit Version
Sometimes the leak is not your fault:
- Early AI Toolkit versions may ship with known memory issues that are fixed later.
Steps:
- Open Package Manager.
- Locate Unity AI Toolkit (or specific AI packages).
- Read:
- Version number
- Release notes / changelog (link on the right).
- Update to the latest verified version for your Unity editor (2026.x).
If you suspect a regression:
- Note the version that leaks vs the last stable one.
- Consider temporarily downgrading while you:
- File a bug report with Unity.
- Isolate a minimal reproduction.
7. Apply General Unity Memory Best Practices Around AI Systems
Even if AI Toolkit is the trigger, standard Unity leak patterns still apply:
- Don’t keep unused ScriptableObjects alive:
- If you load data into singleton objects, clear references when they are not needed.
- Avoid calling
Resources.Loadrepeatedly inside tight loops:- Cache references once; unload when finished.
- Be careful with:
DontDestroyOnLoadobjects that accumulate references to scenes/agents.
Combine these with:
- Periodic GC allocations checks in the Profiler
- Reasonable object pooling for frequently spawned agents
8. Quick Checklist – Before and After Fixes
Use this checklist to track progress:
Before:
- [ ] Memory (Managed Heap / Total Used) climbs steadily over long sessions.
- [ ] Crashes or OS‑level kills on mobile after extended play.
- [ ] AI agents are spawned and destroyed often.
After fixes:
- [ ] AI agents and brains have clear lifetime rules (spawn → use → destroy).
- [ ] No static lists/dictionaries slowly accumulate agent references or logs.
- [ ] Scene reload tests no longer cause unbounded memory growth.
- [ ] AI Toolkit is running on a current, stable version.
- [ ] Profiler shows memory usage stabilizing over time.
If memory still climbs unreasonably:
- Capture a pair of memory snapshots.
- Note:
- Unity version
- AI Toolkit version
- Simplest reproduction scene
- Share them with Unity support or the AI Toolkit issue tracker so they can diagnose engine‑level issues beyond your project code.