加载assetbundle

csharp

浏览数:247

2019-1-7


LoadAssetBundle.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
public class LoadAssetBundle : MonoBehaviour
{

    private string BundleURL;
    public UILabel uilabel;
    public Material mat;
    private void Start()
    {
        //在pc端加载的assetbundle包后缀为“assetbundle” 移动端后缀为“unity3d”
#if UNITY_EDITOR
        StartCoroutine(LoadAsset("文件名.assetbundle", "URL"));
#else
          StartCoroutine(LoadAsset("文件名.unity3d", "URL"));
#endif
    }

    IEnumerator LoadAsset( string FileName,string Url)
    {
        //如果本地有这个asb包则读本地 ,如果没有则下载到本地后再读取
        if (File.Exists(Application.persistentDataPath + "/" + FileName))
        {
            using (WWW asset = new WWW("file:///" +Application.persistentDataPath + "/" + FileName))
            {
                yield return asset;
                AssetBundle bundle = asset.assetBundle;
                //bundle.LoadAsset("文件名")
                GameObject Obj = Instantiate(bundle.LoadAsset("打包前的资源名称")) as GameObject;
                bundle.Unload(false);

                yield return new WaitForSeconds(5);
            }
        }
        else
        {
            using (WWW asset = new WWW(Url))
            {
                yield return asset;
                FileStream f = new FileStream(Application.persistentDataPath + "/" + FileName, FileMode.Create, FileAccess.Write);
                f.Write(asset.bytes, 0, asset.bytes.Length);
                AssetBundle bundle = asset.assetBundle;
                GameObject Obj = Instantiate(bundle.LoadAsset("打包前的资源名称")) as GameObject;
                bundle.Unload(false);

                yield return new WaitForSeconds(5);
            }
        }
        
    }
}