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);//调用kernel32.dll中的GlobalMemoryStatus方法,extern表示引用外部非托管dll

/// <summary>
/// 获取Win环境可用内存
/// </summary>
protected ulong GetWinAvailMemory()
{
MEMORYSTATUSEX ms = new MEMORYSTATUSEX();
ms.dwLength = 64;
GlobalMemoryStatus(ref ms);
return ms.ullAvailPhys;
}
/// <summary>
/// 获取Win总内存
/// </summary>
protected ulong GetWinTotalMemory()
{
MEMORYSTATUSEX ms = new MEMORYSTATUSEX();
ms.dwLength = 64;
GlobalMemoryStatus(ref ms);
return ms.ullTotalPhys;
}
/// <summary>
/// 获取Win环境已用内存
/// </summary>
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一节。