AssetBoundle載入非預設資源

_清風明月發表於2018-12-20
1.定義一個協程LoadNonObjFromAB
IEnumerator LoadNonObjFromAB(string ABURL, GameObject go, string assetName)

引數含義:ABURL:要下載的AB包地址  go:用於測試,顯示載入貼圖  assetName:要載入的資源名稱

IEnumerator LoadNonObjFromAB(string ABURL, GameObject go, string assetName)
        {
            //引數檢查
            if(string.IsNullOrEmpty(ABURL) || go == null)
            {
                Debug.LogError("引數錯誤!");
            }
            using (WWW www = new WWW(ABURL))
            {
                yield return www;
                AssetBundle ab = www.assetBundle;    //獲取AB包
                if(ab != null)
                {
                    if(assetName == "")
                    {
                        go.GetComponent<Renderer>().material.mainTexture = ab.mainAsset as Texture;
                    }
                    else
                    {

                        go.GetComponent<Renderer>().material.mainTexture = (Texture)ab.LoadAsset(assetName);  //替換貼圖為下載的貼圖
                        print(assetName);

                    }
                    //解除安裝AB包
                    ab.Unload(false);
                }
                else
                {
                    Debug.LogError("下載錯誤:"+www.error);
                }
            }
}

2.呼叫協程
 private void Start()
        {
            StartCoroutine(LoadNonObjFromAB(URL1, testGo, assetName1));
        }

(在呼叫之前要對引數初始化)

 

 

相關文章