Created
September 29, 2025 20:12
-
-
Save gilzoide/0361c0b529a62a9fe3e39ecb625708dd to your computer and use it in GitHub Desktop.
Automatic garbage collector for Unity to help debugging memory leaks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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