Skip to content

Instantly share code, notes, and snippets.

@gilzoide
Created September 29, 2025 20:12
Show Gist options
  • Select an option

  • Save gilzoide/0361c0b529a62a9fe3e39ecb625708dd to your computer and use it in GitHub Desktop.

Select an option

Save gilzoide/0361c0b529a62a9fe3e39ecb625708dd to your computer and use it in GitHub Desktop.
Automatic garbage collector for Unity to help debugging memory leaks
using System.Threading.Tasks;
using UnityEngine;
public class AutoGarbageCollector
{
#if !DEVELOPMENT_BUILD
// Collect all memory once per second.
// Runs C# GC, unused assets GC and JVM GC on Android
// Don't use this in production!
[RuntimeInitializeOnLoadMethod]
static async void CollectGarbageLoop()
{
while (Application.isPlaying)
{
await Task.Delay(1000);
Resources.UnloadUnusedAssets();
System.GC.Collect();
#if UNITY_ANDROID && !UNITY_EDITOR
using (var systemClass = new AndroidJavaClass("java.lang.System"))
{
systemClass.CallStatic("gc");
systemClass.CallStatic("runFinalization");
}
#endif
}
}
#endif
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment