This repository was archived by the owner on Oct 28, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMemoryManager.cs
More file actions
78 lines (58 loc) · 2.21 KB
/
Copy pathMemoryManager.cs
File metadata and controls
78 lines (58 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
using System;
using Cysharp.Threading.Tasks;
using UnityEngine;
using UnityEngine.Events;
namespace Argyle.UnclesToolkit
{
public class MemoryManager : Manager<MemoryManager>
{
public float MemoryLimitGB = 4;
const int GB = 1024 * 1024 * 1024;
public static long MemoryLimit => (int) (Instance.MemoryLimitGB * GB);
public static long MemoryUsed { get; private set; }
public static float MemoryLimitUsed { get; private set; }
public UnityEvent OnMemoryLimitReached = new UnityEvent();
public UnityEvent OnUnityLowMemory = new UnityEvent();
#region ==== Monobehavior ====------------------
protected void Start()
{
Application.lowMemory += UnityLowMemoryHandler;
}
public float MemoryCheckFrequency = 5f;
private float _lastCheckTime;
private void Update()
{
if(Time.realtimeSinceStartup - _lastCheckTime > MemoryCheckFrequency)
{
CheckMemoryUsage();
}
}
#endregion -----------------/Monobehavior ====
private void CheckMemoryUsage()
{
//.Log($"MEMORY MANAGER: Checking memory usage at {Time.realtimeSinceStartup} seconds. Memory used: {MemoryUsed / GB} GB");
MemoryUsed = GC.GetTotalMemory(false);
MemoryLimitUsed = MemoryUsed / (float)MemoryLimit;
_lastCheckTime = Time.realtimeSinceStartup;
if (MemoryUsed > MemoryLimit)
{
//Debug.Log($"MEMORY MANAGER: Memory limit reached at {Time.realtimeSinceStartup} seconds. Memory used: {MemoryUsed / GB} GB");
OnMemoryLimitReached.Invoke();
}
//Debug.Log($"MEMORY MANAGER: Finished checking memory usage at {Time.realtimeSinceStartup} seconds. Memory used: {MemoryUsed / GB} GB");
}
public void UnityLowMemoryHandler()
{
//Debug.Log($"Unloading unused assets at {Time.realtimeSinceStartup} seconds. Memory used: {MemoryUsed / GB} GB");
Resources.UnloadUnusedAssets();
//Debug.Log($"Finished Unloading unused assets at {Time.realtimeSinceStartup} seconds. Memory used: {MemoryUsed / GB} GB");
OnUnityLowMemory.Invoke();
ReportOnMemoryCleanup();
}
private async UniTaskVoid ReportOnMemoryCleanup()
{
await UniTask.NextFrame();
Debug.Log($"Frame after Unloading unused assets at {Time.realtimeSinceStartup} seconds. Memory used: {MemoryUsed / GB} GB");
}
}
}