| | 1 | | using System.Collections; |
| | 2 | | using System.Collections.Generic; |
| | 3 | | using UnityEngine; |
| | 4 | | using UnityEngine.Profiling; |
| | 5 | |
|
| | 6 | | namespace DCL |
| | 7 | | { |
| | 8 | | public class MemoryManager : IMemoryManager |
| | 9 | | { |
| | 10 | | private const uint MAX_USED_MEMORY = 1300 * 1024 * 1024; |
| | 11 | | private const float TIME_FOR_NEW_MEMORY_CHECK = 1.0f; |
| | 12 | |
|
| | 13 | | private Coroutine autoCleanupCoroutine; |
| | 14 | |
|
| | 15 | | private uint memoryThresholdForCleanup = 0; |
| | 16 | | private float cleanupInterval; |
| | 17 | |
|
| | 18 | | public event System.Action OnCriticalMemory; |
| | 19 | |
|
| 0 | 20 | | public MemoryManager (uint memoryThresholdForCleanup, float cleanupInterval) |
| | 21 | | { |
| 0 | 22 | | this.memoryThresholdForCleanup = this.memoryThresholdForCleanup; |
| 0 | 23 | | this.cleanupInterval = this.cleanupInterval; |
| 0 | 24 | | autoCleanupCoroutine = CoroutineStarter.Start(AutoCleanup()); |
| 0 | 25 | | } |
| | 26 | |
|
| 666 | 27 | | public MemoryManager () |
| | 28 | | { |
| 666 | 29 | | this.memoryThresholdForCleanup = MAX_USED_MEMORY; |
| 666 | 30 | | this.cleanupInterval = TIME_FOR_NEW_MEMORY_CHECK; |
| 666 | 31 | | autoCleanupCoroutine = CoroutineStarter.Start(AutoCleanup()); |
| 666 | 32 | | } |
| | 33 | |
|
| | 34 | | public void Dispose() |
| | 35 | | { |
| 687 | 36 | | if (autoCleanupCoroutine != null) |
| 666 | 37 | | CoroutineStarter.Stop(autoCleanupCoroutine); |
| | 38 | |
|
| 687 | 39 | | autoCleanupCoroutine = null; |
| 687 | 40 | | } |
| | 41 | |
|
| | 42 | | bool NeedsMemoryCleanup() |
| | 43 | | { |
| 694 | 44 | | long usedMemory = Profiler.GetTotalAllocatedMemoryLong() + Profiler.GetMonoUsedSizeLong() + Profiler.GetAllo |
| 694 | 45 | | return usedMemory >= MAX_USED_MEMORY; |
| | 46 | | } |
| | 47 | |
|
| | 48 | | IEnumerator AutoCleanup() |
| | 49 | | { |
| 28 | 50 | | while (true) |
| | 51 | | { |
| 694 | 52 | | if (NeedsMemoryCleanup()) |
| | 53 | | { |
| 0 | 54 | | OnCriticalMemory?.Invoke(); |
| 0 | 55 | | yield return CleanPoolManager(); |
| 0 | 56 | | Resources.UnloadUnusedAssets(); |
| | 57 | | } |
| | 58 | |
|
| 694 | 59 | | yield return new WaitForSecondsRealtime(TIME_FOR_NEW_MEMORY_CHECK); |
| | 60 | | } |
| | 61 | | } |
| | 62 | |
|
| | 63 | | public IEnumerator CleanPoolManager(bool forceCleanup = false, bool immediate = false) |
| | 64 | | { |
| 0 | 65 | | bool unusedOnly = true; |
| 0 | 66 | | bool nonPersistentOnly = true; |
| | 67 | |
|
| 0 | 68 | | if ( forceCleanup ) |
| | 69 | | { |
| 0 | 70 | | unusedOnly = false; |
| 0 | 71 | | nonPersistentOnly = false; |
| | 72 | | } |
| | 73 | |
|
| 0 | 74 | | if ( immediate ) |
| | 75 | | { |
| 0 | 76 | | PoolManager.i.Cleanup(unusedOnly, nonPersistentOnly); |
| 0 | 77 | | } |
| | 78 | | else |
| | 79 | | { |
| 0 | 80 | | yield return PoolManager.i.CleanupAsync(unusedOnly, nonPersistentOnly, false); |
| | 81 | | } |
| 0 | 82 | | } |
| | 83 | | } |
| | 84 | | } |