PC平台内存获取
我们通过C#的System.Runtime.InteropServices
,通过kernel32.dll
来获取内存信息
与非托管代码进行交互操作 - .NET Framework | Microsoft Learn
Profiling.Profiler - Unity 脚本 API
UnityEngine.Profiling.Profiler
提供的一些函数在运行时调用是不会降低性能的。
修改PlatMsgManager
,在里面添加一些函数和const变量,并修改GetLongFromPlatform
函数
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
| using System.Runtime.InteropServices;
public const int UNITY_GET_LONG_AVAILABLEMEMORY = 1; public const int UNITY_GET_LONG_TOTALEMEMORY = 2; public const int UNITY_GET_LONG_USEDMEMORY = 3; #else
public long GetLongFromPlatform(int type) { switch (type) { case UNITY_GET_LONG_AVAILABLEMEMORY: return (long)GetWinAvailMemory(); case UNITY_GET_LONG_TOTALEMEMORY: return (long)GetWinTotalMemory(); case UNITY_GET_LONG_USEDMEMORY: return GetWinUsedMemory(); } return 0; } #endif
[StructLayout(LayoutKind.Sequential,Pack = 1)] public struct MEMORYSTATUSEX { public uint dwLength; public uint dwMemoryLoad; public ulong ullTotalPhys; public ulong ullAvailPhys; public ulong ullTotalPageFile; public ulong ullAvailPageFile; public ulong ullTotalVirtual; public ulong ullAvailVirtual; public ulong ullAvailExtendedVirtual; } [DllImport("kernel32.dll")] protected static extern void GlobalMemoryStatus(ref MEMORYSTATUSEX lpMemoryStatus);
protected ulong GetWinAvailMemory() { MEMORYSTATUSEX ms = new MEMORYSTATUSEX(); ms.dwLength = 64; GlobalMemoryStatus(ref ms); return ms.ullAvailPhys; } protected ulong GetWinTotalMemory() { MEMORYSTATUSEX ms = new MEMORYSTATUSEX(); ms.dwLength = 64; GlobalMemoryStatus(ref ms); return ms.ullTotalPhys; } protected long GetWinUsedMemory() { return UnityEngine.Profiling.Profiler.GetTotalReservedMemoryLong(); }
|
测试
在GameStart
里面添加
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| protected override void Awake() { base.Awake(); PlatMsgManager.Instance.Init(); DontDestroyOnLoad(gameObject); Debug.LogFormat( "系统总内存:{0}mb" + "\n" + "系统可用内存:{1}mb" + "\n" + "已用内存:{2}mb", PlatMsgManager.Instance.GetLongFromPlatform(2) / (1024.0f * 1024.0f), PlatMsgManager.Instance.GetLongFromPlatform(1) / (1024.0f * 1024.0f), PlatMsgManager.Instance.GetLongFromPlatform(3) / (1024.0f * 1024.0f)); }
|
安卓平台内存获取
详情请看GameHelper一节。