|
| 1 | +using System.Collections.Generic; |
| 2 | +using TMPro; |
| 3 | +using UnityEngine; |
| 4 | + |
| 5 | +public class MemoryDevConsole : MonoBehaviour { |
| 6 | + [Min(0.25f)] |
| 7 | + [Tooltip("Seconds between data refreshes")] |
| 8 | + public float refreshRate = 1; |
| 9 | + |
| 10 | + public LuauContext context = LuauContext.Game; |
| 11 | + |
| 12 | + public GameObject logInstance; |
| 13 | + |
| 14 | + private float _lastRefreshTime; |
| 15 | + private Dictionary<LuauContext, List<LuauPlugin.LuauMemoryCategoryDumpItem>> _dumps; |
| 16 | + |
| 17 | + private static string FormatBytes(ulong bytes) { |
| 18 | + if (bytes < 1024) { |
| 19 | + return $"{bytes} B"; |
| 20 | + } |
| 21 | + |
| 22 | + if (bytes < 1024L * 1024L) { |
| 23 | + return $"{(bytes / 1024f):F2} KB"; |
| 24 | + } |
| 25 | + |
| 26 | + if (bytes < 1024 * 1024L * 1024L) { |
| 27 | + return $"{(bytes / (1024f * 1024f)):F2} MB"; |
| 28 | + } |
| 29 | + |
| 30 | + return $"{(bytes / (1024f * 1024f * 1024f)):F2} GB"; |
| 31 | + } |
| 32 | + |
| 33 | + private void Start() { |
| 34 | + _lastRefreshTime = Time.unscaledTime; |
| 35 | + _dumps = new Dictionary<LuauContext, List<LuauPlugin.LuauMemoryCategoryDumpItem>> { |
| 36 | + [LuauContext.Game] = new(), |
| 37 | + [LuauContext.Protected] = new(), |
| 38 | + }; |
| 39 | + } |
| 40 | + |
| 41 | + private void Update() { |
| 42 | + var now = Time.unscaledTime; |
| 43 | + if (now - _lastRefreshTime < refreshRate) { |
| 44 | + return; |
| 45 | + } |
| 46 | + |
| 47 | + _lastRefreshTime = now; |
| 48 | + |
| 49 | + Refresh(); |
| 50 | + } |
| 51 | + |
| 52 | + private List<TMP_InputField> _logItems = new(); |
| 53 | + private void Refresh() { |
| 54 | + LuauPlugin.LuauGetMemoryCategoryDump(context, _dumps[context]); |
| 55 | + |
| 56 | + var sortedDump = new List<LuauPlugin.LuauMemoryCategoryDumpItem>(_dumps[context]); |
| 57 | + sortedDump.Sort(((itemA, itemB) => itemA.Bytes == itemB.Bytes ? 0 : itemA.Bytes < itemB.Bytes ? 1 : -1)); |
| 58 | + |
| 59 | + var i = 0; |
| 60 | + foreach (var item in sortedDump) { |
| 61 | + TMP_InputField instance; |
| 62 | + if (i < _logItems.Count) { |
| 63 | + instance = _logItems[i]; |
| 64 | + } else { |
| 65 | + instance = Instantiate(logInstance, transform).GetComponent<TMP_InputField>(); |
| 66 | + _logItems.Add(instance); |
| 67 | + } |
| 68 | + instance.text = $"{item.ShortName}: {FormatBytes(item.Bytes)}"; |
| 69 | + i++; |
| 70 | + } |
| 71 | + |
| 72 | + while (_logItems.Count > i) { |
| 73 | + Destroy(_logItems[^1].gameObject); |
| 74 | + _logItems.RemoveAt(_logItems.Count - 1); |
| 75 | + } |
| 76 | + } |
| 77 | +} |
0 commit comments