适用于 Unity 游戏的 Memory Advice API 使用入门

本指南介绍了如何使用适用于 Unity 的 Memory Advice 插件将 Memory Advice API 集成到您的 Unity 游戏中。

要求

以下版本支持该插件:

  • 安装 Android NDK r19 的 Unity 2019

  • 安装 Android NDK r19 的 Unity 2020

  • 安装 Android NDK r21 的 Unity 2021

  • 安装 Android NDK r23 的 Unity 2022

如果您使用的是其他版本的 Unity 和 Android NDK,可能会遇到意外问题。如需查找您的 Unity 安装使用的 NDK 版本,请参阅适用于 Unity 的 Android 环境设置指南

下载插件

下载插件

导入插件

此插件是一个 Unity 软件包,您可以在项目中导入该软件包。如需导入该插件,请依次点击 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,并在状态接近上限或紧急内存状态(但不适用于 ok 状态)时调用 watcher 函数。例如,以下代码会创建一个观察器并每 2 秒请求一次 Memory Advice API 通知:

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 示例项目,该项目提供了用于分配和释放内存的简单界面,并使用 Memory Advice API 监控内存状态。

如需查看其他资源报告问题,请参阅概览