Unity加载AB包(缓存)

36 篇文章 1 订阅
   /// <summary>
    /// load assetbundle manifest, check hash, load actual bundle with hash parameter to use caching
    /// instantiate gameobject
    /// </summary>
    /// <param name="bundleURL">full url to assetbundle file</param>
    /// <param name="assetName">optional parameter to access specific asset from assetbundle</param>
    /// <returns></returns>
    IEnumerator DownloadAndCache(string bundleURL, string assetName = "")
    {
        // Wait for the Caching system to be ready
        while (!Caching.ready)
        {
            yield return null;
        }

        // if you want to always load from server, can clear cache first
        //        Caching.CleanCache();

        // get current bundle hash from server, random value added to avoid caching
        UnityWebRequest www = UnityWebRequest.Get(bundleURL + ".manifest");
        Debug.Log("Loading manifest:" + bundleURL + ".manifest");

        // wait for load to finish
        yield return www.SendWebRequest();

        // if received error, exit
        if (www.result != UnityWebRequest.Result.Success)
        {
            Debug.LogError("www error: " + www.error);
            www.Dispose();
            www = null;
            yield break;
        }

        // create empty hash string
        Hash128 hashString = (default(Hash128));// new Hash128(0, 0, 0, 0);

        // check if received data contains 'ManifestFileVersion'
        if (www.downloadHandler.text.Contains("ManifestFileVersion"))
        {
            // extract hash string from the received data, TODO should add some error checking here
            var hashRow = www.downloadHandler.text.ToString().Split("\n".ToCharArray())[5];
            hashString = Hash128.Parse(hashRow.Split(':')[1].Trim());

            if (hashString.isValid == true)
            {
                // we can check if there is cached version or not
                if (Caching.IsVersionCached(bundleURL, hashString) == true)
                {
                    Debug.Log("Bundle with this hash is already cached!");
                }
                else
                {
                    Debug.Log("No cached version founded for this hash..");
                }
            }
            else
            {
                // invalid loaded hash, just try loading latest bundle
                Debug.LogError("Invalid hash:" + hashString);
                yield break;
            }

        }
        else
        {
            Debug.LogError("Manifest doesn't contain string 'ManifestFileVersion': " + bundleURL + ".manifest");
            yield break;
        }

        // now download the actual bundle, with hashString parameter it uses cached version if available
        www = UnityWebRequestAssetBundle.GetAssetBundle(bundleURL, hashString, 0);

        // wait for load to finish
        yield return www.SendWebRequest();

        if (www.error != null)
        {
            Debug.LogError("www error: " + www.error);
            www.Dispose();
            www = null;
            yield break;
        }

        // get bundle from downloadhandler
        AssetBundle bundle = ((DownloadHandlerAssetBundle)www.downloadHandler).assetBundle;

        GameObject bundlePrefab = null;

        // if no asset name is given, take the first/main asset
        if (assetName == "")
        {
            bundlePrefab = (GameObject)bundle.LoadAsset(bundle.GetAllAssetNames()[0]);
        }
        else
        { // use asset name to access inside bundle
            bundlePrefab = (GameObject)bundle.LoadAsset(assetName);
        }

        // if we got something out
        if (bundlePrefab != null)
        {

            // instantiate at 0,0,0 and without rotation
            Instantiate(bundlePrefab, Vector3.zero, Quaternion.identity);

            /*
            // fix pink shaders, NOTE: not always needed..
            foreach (Renderer r in go.GetComponentsInChildren<Renderer>(includeInactive: true))
            {
                // FIXME: creates multiple materials, not good
                var material = Shader.Find(r.material.shader.name);
                r.material.shader = null;
                r.material.shader = material;
            }*/
        }

        www.Dispose();
        www = null;

        // try to cleanup memory
        Resources.UnloadUnusedAssets();
        bundle.Unload(false);
        bundle = null;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值