|
3 | 3 | using System.Collections.Generic; |
4 | 4 | using Unity.UIWidgets.external.simplejson; |
5 | 5 | using Unity.UIWidgets.foundation; |
| 6 | +using Unity.UIWidgets.rendering; |
6 | 7 | using Unity.UIWidgets.ui; |
7 | 8 | using Unity.UIWidgets.widgets; |
8 | 9 | using UnityEngine; |
9 | 10 | using UnityEngine.EventSystems; |
| 11 | +using UnityEngine.Profiling; |
| 12 | +using UnityEngine.Scripting; |
10 | 13 | using UnityEngine.UI; |
11 | 14 | using RawImage = UnityEngine.UI.RawImage; |
12 | 15 |
|
@@ -147,16 +150,41 @@ void _handleViewMetricsChanged(string method, List<JSONNode> args) { |
147 | 150 | } |
148 | 151 | } |
149 | 152 |
|
| 153 | + // 8 MB |
| 154 | + const long kCollectAfterAllocating = 8 * 1024 * 1024; |
| 155 | + |
| 156 | + long lastFrameMemory = 0; |
| 157 | + long nextCollectAt = 0; |
| 158 | + |
150 | 159 | protected virtual void Update() { |
151 | 160 | if (!_viewMetricsCallbackRegistered) { |
152 | 161 | _viewMetricsCallbackRegistered = true; |
153 | 162 | UIWidgetsMessageManager.instance?.AddChannelMessageDelegate("ViewportMetricsChanged", |
154 | 163 | _handleViewMetricsChanged); |
155 | 164 | } |
| 165 | + |
| 166 | + CollectGarbegeOndemend(); |
156 | 167 |
|
157 | 168 | Input_Update(); |
158 | 169 | } |
159 | 170 |
|
| 171 | + void CollectGarbegeOndemend() { |
| 172 | + long mem = Profiler.GetMonoUsedSizeLong(); |
| 173 | + if (mem < lastFrameMemory) |
| 174 | + { |
| 175 | + // GC happened. |
| 176 | + nextCollectAt = mem + kCollectAfterAllocating; |
| 177 | + } |
| 178 | + else if (mem >= nextCollectAt) |
| 179 | + { |
| 180 | + // Trigger incremental GC |
| 181 | + GarbageCollector.CollectIncremental(1000); |
| 182 | + lastFrameMemory = mem + kCollectAfterAllocating; |
| 183 | + } |
| 184 | + |
| 185 | + lastFrameMemory = mem; |
| 186 | + } |
| 187 | + |
160 | 188 | #if !UNITY_EDITOR && UNITY_ANDROID |
161 | 189 | bool AndroidInitialized = true; |
162 | 190 |
|
@@ -185,6 +213,11 @@ protected void OnEnable() { |
185 | 213 | //the hook API cannot be automatically called on IOS, so we need try hook it here |
186 | 214 | Hooks.tryHook(); |
187 | 215 | #endif |
| 216 | +#if !UNITY_EDITOR |
| 217 | + GarbageCollector.GCMode = GarbageCollector.Mode.Disabled; |
| 218 | +#endif |
| 219 | + Application.lowMemory += GC.Collect; |
| 220 | + |
188 | 221 | base.OnEnable(); |
189 | 222 |
|
190 | 223 | D.assert(_wrapper == null); |
|
0 commit comments