欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

AssetBundle加载的四种方式

程序员文章站 2022-05-15 18:41:53
...
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;

public class LoadFromFileExample : MonoBehaviour {

    string path;
   
	void Start () {


        path = "AssetBundle/scene/cubewall.unity3d";//路径
        AssetBundle.LoadFromFile("AssetBundle/material/wood.unity3d");//加载依赖贴图,材质

        //  StartCoroutine(LoadAssetBundleFromMemoryAsync());
        //  LoadAssetBundleFromMemory();
        //  LoadFromFile();
          StartCoroutine(LoadFromFileAsyn());
    }


    #region 第一种类型

    //第一种加载异步
    IEnumerator LoadAssetBundleFromMemoryAsync()
    {
        AssetBundleCreateRequest createRequest = AssetBundle.LoadFromMemoryAsync(File.ReadAllBytes(path));
        yield return createRequest;
        AssetBundle AB = createRequest.assetBundle;
        GameObject obj = AB.LoadAsset<GameObject>("cube");
        Instantiate(obj);
    }
    //第一种同步加载
    private void LoadAssetBundleFromMemory()
    {
         AssetBundle AB= AssetBundle.LoadFromMemory(File.ReadAllBytes(path));
         GameObject obj = AB.LoadAsset<GameObject>("cube");
        Instantiate(obj); 
    }

    #endregion

    #region 第二种类型
    //同步加载
    void LoadFromFile()
    {
        AssetBundle AB = AssetBundle.LoadFromFile(path);
        if (AB == null)
        {
            Debug.LogWarning("Fail to load AssetBundle");
            return;
        }
        GameObject obj = AB.LoadAsset<GameObject>("cube");
        Instantiate(obj);
    }
    //异步加载
    IEnumerator LoadFromFileAsyn()
    {
         AssetBundleCreateRequest createRequest=AssetBundle.LoadFromFileAsync(path);
        yield return createRequest;

        AssetBundle AB = createRequest.assetBundle;
        if (AB == null)
        {
            Debug.LogWarning("Fail to load AssetBundle");
            yield break;
        }

       AssetBundleRequest Request = AB.LoadAssetAsync<GameObject>("cube");
        yield return Request;
        if (Request == null)
        {
            Debug.LogWarning("Fail to load Request");
            yield break;
        }
        GameObject obj = Request.asset as GameObject;
        Instantiate(obj);

    }

    #endregion
}

 

相关标签: unity AssetBundle