| | | 1 | | // Copyright (c) 2020-2024 dotBunny Inc. |
| | | 2 | | // dotBunny licenses this file to you under the BSL-1.0 license. |
| | | 3 | | // See the LICENSE file in the project root for more information. |
| | | 4 | | |
| | | 5 | | using System; |
| | | 6 | | using System.Runtime.CompilerServices; |
| | | 7 | | using System.Threading.Tasks; |
| | | 8 | | using UnityEngine; |
| | | 9 | | |
| | | 10 | | namespace GDX |
| | | 11 | | { |
| | | 12 | | /// <summary> |
| | | 13 | | /// A collection of memory related helper utilities. |
| | | 14 | | /// </summary> |
| | | 15 | | [VisualScriptingCompatible(8)] |
| | | 16 | | public static class Memory |
| | | 17 | | { |
| | | 18 | | /// <summary> |
| | | 19 | | /// <para>Cleanup Memory</para> |
| | | 20 | | /// <list type="bullet"> |
| | | 21 | | /// <item> |
| | | 22 | | /// <description>Mono Heap (Garbage Collection)</description> |
| | | 23 | | /// </item> |
| | | 24 | | /// <item> |
| | | 25 | | /// <description>Unity Resources (when not deployed on DOTS Runtime.</description> |
| | | 26 | | /// </item> |
| | | 27 | | /// </list> |
| | | 28 | | /// </summary> |
| | | 29 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 30 | | public static void CleanUp() |
| | 0 | 31 | | { |
| | | 32 | | // Fire off a first pass collection |
| | 0 | 33 | | GC.Collect(); |
| | | 34 | | |
| | | 35 | | // Tell Unity to clean up any assets that it no longer wants to have loaded |
| | | 36 | | #if !UNITY_DOTSRUNTIME |
| | 0 | 37 | | Resources.UnloadUnusedAssets(); |
| | | 38 | | #endif // !UNITY_DOTSRUNTIME |
| | | 39 | | |
| | | 40 | | // Fire off second pass collection |
| | 0 | 41 | | GC.WaitForPendingFinalizers(); |
| | 0 | 42 | | GC.Collect(); |
| | 0 | 43 | | } |
| | | 44 | | |
| | | 45 | | #if !UNITY_DOTSRUNTIME |
| | | 46 | | /// <inheritdoc cref="CleanUp" /> |
| | | 47 | | /// <exception cref="UnsupportedRuntimeException">Not supported on DOTS Runtime.</exception> |
| | | 48 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 49 | | public static async void CleanUpAsync() |
| | 0 | 50 | | { |
| | | 51 | | // Fire off a first pass collection |
| | 0 | 52 | | GC.Collect(); |
| | | 53 | | |
| | | 54 | | // Tell Unity to clean up any assets that it no longer wants to have loaded |
| | 0 | 55 | | AsyncOperation handle = Resources.UnloadUnusedAssets(); |
| | 0 | 56 | | while (!handle.isDone) |
| | 0 | 57 | | { |
| | 0 | 58 | | await Task.Delay(1000); |
| | 0 | 59 | | } |
| | | 60 | | |
| | | 61 | | // Fire off second pass collection |
| | 0 | 62 | | GC.WaitForPendingFinalizers(); |
| | 0 | 63 | | GC.Collect(); |
| | 0 | 64 | | } |
| | | 65 | | #endif // !UNITY_DOTSRUNTIME |
| | | 66 | | } |
| | | 67 | | } |