1.PC平台
[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;
}
//extern 调用 其他平台 dll 关键字
[DllImport("kernel32.dll")]
protected static extern void GlobalMemoryStatus(ref MEMORYSTATUSEX lpBuff);
/// <summary>
/// 获取可用内存
/// PC
/// </summary>
/// <returns></returns>
protected ulong GetWinAvailMemory()
{
MEMORYSTATUSEX ms = new MEMORYSTATUSEX();
ms.dwLength = 64;
GlobalMemoryStatus(ref ms);
return ms.ullAvailPhys;
}
/// <summary>
/// 获取总内存
/// PC
/// </summary>
/// <returns></returns>
protected ulong GetWinTotalMemory()
{
MEMORYSTATUSEX ms = new MEMORYSTATUSEX();
ms.dwLength = 64;
GlobalMemoryStatus(ref ms);
return ms.ullTotalPhys;
}
/// <summary>
/// 返回应用使用的内存
/// PC
/// </summary>
/// <returns></returns>
protected long GetWinUsedMemory()
{
return UnityEngine.Profiling.Profiler.GetTotalReservedMemoryLong();
}
内存快爆掉了。。。。
2.Android端
//当前系统可用内存
ActivityManager am =
(ActivityManager)m_Activity.getSystemService(Context.ACTIVITY_SERVICE);
MemoryInfo mi= new MemoryInfo();
am.getMemoryInfo(mi);
return mi.availMem;
//当前系统总内存
return GetTotalMemory();
//应用所占内存
Debug.MemoryInfo memoryInfo=new Debug.MemoryInfo();
Debug.getMemoryInfo(memoryInfo);
return memoryInfo.getTotalPss()*1024;
3.IOS
using System;
using System.Runtime.InteropServices;
using UnityEngine;
public class IOSMemoryUsage : MonoBehaviour
{
[DllImport("__Internal")]
private static extern int task_info(int target_task, int task_info_flavor, ref IntPtr task_info_out, ref uint task_info_outCnt);
[DllImport("__Internal")]
private static extern int mach_task_self();
private const int TASK_VM_INFO = 22; // 根据实际需求可以修改task_info_flavor的值
private void Start()
{
long memoryUsage = GetMemoryUsage();
Debug.Log("IOS Memory Usage: " + memoryUsage + " bytes");
}
private long GetMemoryUsage()
{
IntPtr taskInfoPtr = IntPtr.Zero;
uint taskInfoSize = 0;
task_info(mach_task_self(), TASK_VM_INFO, ref taskInfoPtr, ref taskInfoSize);
TASK_VM_INFO taskInfo = (TASK_VM_INFO)Marshal.PtrToStructure(taskInfoPtr, typeof(TASK_VM_INFO));
Marshal.FreeHGlobal(taskInfoPtr);
return taskInfo.phys_footprint;
}
}
[StructLayout(LayoutKind.Sequential)]
public struct TASK_VM_INFO
{
public uint virtual_size;
public uint resident_size;
public uint resident_size_max;
public uint shared_clean;
public uint private_clean;
public uint shared_dirty;
public uint private_dirty;
public uint phys_footprint;
public uint min_address;
public uint max_address;
}