開始使用 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 版本,請參閱 這個 Android 環境設定指南 Unity 應用程式

下載外掛程式

下載外掛程式

匯入外掛程式

外掛程式是您可以在專案中匯入的 Unity 套件。匯入 ,按一下素材資源>匯入套件 >「Custom Package」,然後選取 已下載的 .unitypackage 個檔案。您也可以按兩下 .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,以及監看指令碼 當狀態接近上限或 記憶體狀態 (但如果是正常狀態的話)。舉例來說,以下程式碼會建立看守工具並每 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 監控記憶體狀態。

請參閱總覽,瞭解其他資源以及如何回報問題