本指南說明如何設定 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");
    }
}
記憶體狀態輪詢
以您選擇的時間間隔輪詢程式庫,即可擷取應用程式的記憶體狀態。每當您需要輪詢程式庫時,請使用 MemoryAdtip_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 Adtip 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 監控記憶體狀態。
