本指南介绍了如何使用适用于 Unity 的 Memory Advice 插件,将 Memory Advice API 集成到您的 Unity 游戏中。
要求
该插件支持:
Unity 2019 和 Android NDK r19
Unity 2020 和 Android NDK r19
Unity 2021 和 Android NDK r21
Unity 2022 和 Android NDK r23
如果您使用其他版本的 Unity 和 Android NDK,可能会遇到意外问题。要查找您的 Unity 安装所使用的 NDK 版本,请参阅 Unity 的Android 环境设置指南。
下载插件
下载插件。
导入插件
该插件是一个 Unity Package,您可以将其导入您的项目。要导入插件,请依次点击 Assets > Import Package > Custom Package,然后选择您下载的 .unitypackage
文件。您也可以在打开 Unity 项目后双击 .unitypackage
文件。
使用库
本部分介绍如何使用该库。
初始化库
您需要在应用启动时初始化该库一次。为此,请将以下代码添加到您的项目中:
void Start()
{
MemoryAdviceErrorCode errorCode = MemoryAdvice.Init();
if(errorCode == MemoryAdviceErrorCode.Ok)
{
Debug.Log("Memory advice init successfully");
}
}
轮询内存状态
您可以按照您选择的间隔轮询库,以检索应用的内存状态。每当您需要轮询库时,请使用 MemoryAdvice_getMemoryState 函数。
MemoryState memoryState = MemoryAdvice.GetMemoryState();
switch (memoryState)
{
case MemoryState.Ok:
//The application can safely allocate memory.
break;
case MemoryState.ApproachingLimit:
// The application should minimize memory allocation.
break;
case MemoryState.Critical:
// The application should free memory as soon as possible
// until the memory state changes.
break;
}
设置观察程序
您还可以设置观察程序并注册 Memory Advice API,当内存状态接近限制或达到临界内存状态时(“正常”状态除外),您的观察程序函数将被调用。例如,以下代码创建一个观察程序并请求 Memory Advice API 每 2 秒发送一次通知。
MemoryAdviceErrorCode errorCode = MemoryAdvice.RegisterWatcher(2000,
new MemoryWatcherDelegateListener((MemoryState state) =>
{
switch (memoryState)
{
case MemoryState.ApproachingLimit:
// The application should minimize memory allocation.
break;
case MemoryState.Critical:
// The application should free memory as soon as possible
// until the memory state changes.
break;
}
})
);
if(errorCode == MemoryAdviceErrorCode.Ok)
{
Debug.Log("Memory Advice watcher registered successfully");
}
下一步
您可以下载我们的 Unity 示例项目,该项目提供了一个简单的 UI 用于分配和释放内存,并使用 Memory Advice API 监控内存状态。