Unity 2022.3.20f1新功能,異步實例化預製體Object.InstantiateAsync

今天查看Unity 2022.3.20f1更新日誌,發現新增了個異步實例化的功能,這個功能解決了Unity歷史上實例化預製體卡頓的痛點,簡直不要太爽。

具體的API文檔請點擊跳轉。

做了個簡單的實例化測試,實例化500*500個Cube,耗時9.2s。實例化過程之間不會卡頓,可以做其他事情,即便是在重度遊戲加載場景過程中也不需要擔心卡頓掉幀影響操作了。測試代碼如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObjTest : MonoBehaviour
{
    public GameObject obj;

    // Start is called before the first frame update
    void Start()
    {
        StartCoroutine(Test());
        Debug.LogError($"test InstantiateAsync");
    }

    IEnumerator Test()
    {
        float startTime = Time.realtimeSinceStartup;
        for (int i = 0; i < 500; i++)
        {
            AsyncInstantiateOperation<GameObject> instantiateOperation = Object.InstantiateAsync(obj, 500);
            yield return instantiateOperation;
            if (instantiateOperation.isDone)
            {
                // Debug.Log($"{instantiateOperation.Result.Length}");
                for (int j = 0; j < instantiateOperation.Result.Length; j++)
                {
                    GameObject go = instantiateOperation.Result[j];
                    go.name = $"cube{i}-{j}";
                }
            }
        }
        Debug.LogError($"spend time:{Time.realtimeSinceStartup - startTime} seconds");
    }

}

創建一個cube拖成預製體,拖拽到腳本上,運行遊戲,可以看到cube一個個在Hierachy視圖逐個創建出來,期間可以拖動滾動條查看,不會卡。

可惜當前項目沒能用這個版本,不過後續新項目能用上新版本,用異步實例化絕對是爽翻天。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章