Unity3d基础:加载AssetBundle资源

//通过AssetBundle资源名字加载并创建物体   

  1. public GameObject CreateAndLoadAssetBundle(string bundleName,string objName=null)
  2.     {
  3.         //路径
  4.         string url = Application.dataPath + "/" +  "StreamingAssets/"  + bundleName.ToLower() + ".assetbundle";
  5.         byte[] stream = File.ReadAllBytes(url);
  6. ---------------------------------------------------------------------------------------------------------------------------
  7.         //从内存 异步加载
  8.          AssetBundleCreateRequest request = AssetBundle.LoadFromMemoryAsync(stream);
  9.         AssetBundle bundle =request.assetBundle;
  10. ---------------------------------------------------------------------------------------------------------------------------       
  11.         //同步加载资源,从内存加载
  12.         AssetBundle bundle = AssetBundle.LoadFromMemory(stream);
  13. --------------------------------------------------------------------------------------------------------------------------
  14.         //异步从本地加载
  15.          AssetBundleCreateRequest request = AssetBundle.LoadFromFileAsync(url);
  16.         AssetBundle bundle =request.assetBundle;
  17. --------------------------------------------------------------------------------------------------------------------------
  18.        //从本地加载
  19.          AssetBundle bundle = AssetBundle.LoadFromFile(url);
  20. ---------------------------------------------------------------------------------------------------------------------------
  21.         //使用WWW类加载
  22.          WWW www = WWW.LoadFromCacheOrDownload(url,1);
  23.          AssetBundle bundle =www.assetBundle;
  24. ---------------------------------------------------------------------------------------------------------------------------
  25.         //UnityWebRequest下载可代替www
  26.         UnityWebRequest request = UnityWebRequest.GetAssetBundle(url);
  27.          AssetBundle bundle = (request.downloadHandler as DownloadHandlerAssetBundle).assetBundle;
  28. ---------------------------------------------------------------------------------------------------------------------------
  29.         GameObject prefab = null;
  30.         if (bundle==null)
  31.         {
  32.             return null;
  33.         }
  34.         //按照名字加载
  35.         if (objName!=null)
  36.         {
  37.             prefab = bundle.LoadAsset(objName,typeof(GameObject))as GameObject;
  38.         }//默认
  39.         else
  40.         {
  41.             prefab = bundle.mainAsset as GameObject;
  42.         }
  43.         //创建物体
  44.         GameObject go = GameObject.Instantiate(prefab)as GameObject;
  45.         go.name = bundleName;
  46.         //释放AssetBundel资源
  47.         bundle.Unload(false);
  48.         return go;      
  49.     }

你可能感兴趣的:(unity3d,C#,菜鸟学习编程之路)