下载和加载本地Assetbundle

2018-09-13  本文已影响0人  90qq
    string url;
    string path;

    WWW wwwAsset;

    public Image progressImg;
    public Text text;
    void Start () {
        url = "http://..../AssetBundles/";
        path = Application.dataPath + "/Resources/";
    }
    
    
    void Update () {//显示下载进度
        if (wwwAsset != null)
        {
            if (!wwwAsset.isDone)
            {
                text.text = (int)(wwwAsset.progress * 100.0) + "%";
                progressImg.fillAmount = wwwAsset.progress;
            }
            else
            {
                progressImg.fillAmount = 1;
            }
        }
    }

    public void DownloadPic1()
    {
        StartCoroutine(DownLoadAssetsWithDependencies2Local(ur, "pic1.ab",path));
        //
    }

    public void OnLoadABClick()
    {
        StartCoroutine(LoadAb("timg.jpg", "indoor1", path + "pic1.ab"));
    }


    /// <summary>
    /// 加载本地Assetbundle,也可以从服务器加载
    /// </summary>
    /// <param name="resName">原本文件的名字</param>
    /// <param name="potalName"></param>
    /// <param name="path1">加载路径</param>
    /// <returns></returns>
    IEnumerator LoadAb(string resName, string potalName, string path1)
    {
        AssetBundleCreateRequest request = AssetBundle.LoadFromMemoryAsync(File.ReadAllBytes(path1));
        yield return request;
        AssetBundle ab = request.assetBundle;
        Cubemap cubemap = ab.LoadAsset<Cubemap>(resName);
        //或者GameObject cubemap = ab.LoadAsset<GameObject>(resName);
        GameObject.Find(potalName).GetComponent<MeshRenderer>().material.SetTexture("_Tex", cubemap);
    }


    /// <summary>
    ///   //从服务器下载到本地
    /// </summary>
    /// <param name="AssetsHost">服务器路径</param>
    /// <param name="AssetName">请求资源名称</param>
    /// <param name="saveLocalPath">保存到本地路径,一般存在Application.persistentDataPath</param>
    /// <returns></returns>
    IEnumerator DownLoadAssetsWithDependencies2Local(string AssetsHost, string AssetName, string saveLocalPath)
    {
        wwwAsset = new WWW(AssetsHost + "/" + AssetName);
        //获取加载进度
        yield return wwwAsset;
        
        //保存到本地
        Stream sw = null;
        FileInfo fileInfo = new FileInfo(saveLocalPath + "/" + AssetName);
        if (fileInfo.Exists)
        {
            fileInfo.Delete();
        }

        //如果此文件不存在则创建
        sw = fileInfo.Create();
        //写入
        sw.Write(wwwAsset.bytes, 0, wwwAsset.bytes.Length);

        sw.Flush();
        //关闭流
        sw.Close();
        //销毁流
        sw.Dispose();

        Debug.Log(name + "成功保存到本地~");
    }


参考自https://blog.csdn.net/cuiyh1993/article/details/52245337

上一篇 下一篇

猜你喜欢

热点阅读