Esempio n. 1
0
    public IEnumerator GetAssetBundle()
    {
        UnityWebRequest www = UnityWebRequestAssetBundle.GetAssetBundle("https://github.com/luk3Sky/unity-ar-test/raw/main/Unity%20Vuforia%20AR%20Project/Assets/AssetBundles/pikachu-Android");

        yield return(www.SendWebRequest());

        if (www.result != UnityWebRequest.Result.Success)
        {
            Debug.Log(www.error);
        }
        else
        {
            AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(www);
            Debug.Log("LOADED BUNDLE: " + bundle);
            string cachePath = Caching.defaultCache.path;
            Debug.Log(cachePath + "\n" + Caching.defaultCache + "\n" + Application.dataPath);

            /*FileInfo[] files = new DirectoryInfo(cachePath).GetFiles();
             * string str = "";
             * foreach (FileInfo file in files)
             * {
             *  str = str + ", " + file.Name;
             *  Debug.Log(str);
             * }*/
            GameObject obj = bundle.LoadAsset <GameObject>(myAsset);

            /*Debug.Log("Type: " + mTrackableBehaviour.GetType() + "\n" + "Component: " + mTrackableBehaviour.GetComponent<GameObject>());
             * GameObject targetObject = mTrackableBehaviour.GetComponent<GameObject>();*/
            Vector3    position = transform.position;
            Quaternion rotation = transform.rotation;
            Vector3    scale    = transform.localScale;
            Debug.Log("Position: " + position + "\nRotation: " + rotation + "\nScale: " + scale);

            /*imageTarget = (ImageTarget)FindObjectOfType(typeof(ImageTarget));
             * Debug.Log("Image Target: " + imageTarget);*/
            objTrf            = Instantiate(obj).transform;
            objTrf.position   = position;
            objTrf.rotation   = rotation;
            objTrf.localScale = scale;
            objTrf.parent     = mTrackableBehaviour.transform;
            if (visibility)
            {
                objTrf.gameObject.SetActive(true);
            }
            else
            {
                objTrf.gameObject.SetActive(false);
            }
            bundle.Unload(false);
        }
    }
Esempio n. 2
0
        private IEnumerator Run()
        {
            if (null == holder)
            {
                isFinished = true;
                yield break;
            }

            string bundlePath = BundleConfig.GetBundlePath(holder.Info.path);

            if (bundlePath == null)
            {
                isFinished = true;
                OnBundleLoaded(null);
                yield break;
            }
            if (AppEnv.ResLog)
            {
                this.Msg($"start load file {PathIdProfile.Ins.GetPath(holder.Info.path)}");
            }
            if (bundlePath.Contains("://"))
            {
                using (wwwRequest = UnityWebRequestAssetBundle.GetAssetBundle(bundlePath))
                {
                    yield return(wwwRequest.SendWebRequest());

                    loadCouroutine = null;
                    if (null == wwwRequest.error)
                    {
                        AssetBundle assetBundle = DownloadHandlerAssetBundle.GetContent(wwwRequest);
                        OnBundleLoaded(assetBundle);
                    }
                    else
                    {
                        this.Warning($"fail to load file {holder.Info.path}");
                        OnBundleLoaded(null);
                    }
                    wwwRequest.Dispose();
                }
                wwwRequest = null;
            }
            else
            {
                diskRequest = AssetBundle.LoadFromFileAsync(bundlePath);
                yield return(diskRequest);

                loadCouroutine = null;
                OnBundleLoaded(diskRequest.assetBundle);
                diskRequest = null;
            }
        }
Esempio n. 3
0
        static IEnumerator ReloadBundle(string bundleName, LoadedBundle loadedBundle)
        {
            if (LogMessages)
            {
                Debug.Log($"Start Reloading Bundle {bundleName}");
            }
            var bundleReq = loadedBundle.IsLocalBundle? UnityWebRequestAssetBundle.GetAssetBundle(loadedBundle.LoadPath) :
                            UnityWebRequestAssetBundle.GetAssetBundle(loadedBundle.LoadPath, new CachedAssetBundle(bundleName, loadedBundle.Hash));

            loadedBundle.IsReloading = true;
            yield return(bundleReq.SendWebRequest());

            loadedBundle.IsReloading = false;

            if (!Utility.CheckRequestSuccess(bundleReq))
            {
                Debug.LogError($"Bundle reload error { bundleReq.error }");
                yield break;
            }

            if (!s_AssetBundles.TryGetValue(bundleName, out var currentLoadedBundle) || currentLoadedBundle.Hash != loadedBundle.Hash)
            {
                if (LogMessages)
                {
                    Debug.Log("Bundle To Reload does not exist(changed during loaing)");
                }
                bundleReq.Dispose();
                yield break;
            }

            //if we can swap now
            if (!s_BundleRefCounts.TryGetValue(bundleName, out var refCount) || refCount == 0)
            {
                if (LogMessages)
                {
                    Debug.Log($"Reloaded Bundle {bundleName}");
                }
                loadedBundle.Bundle.Unload(true);
                loadedBundle.Bundle = DownloadHandlerAssetBundle.GetContent(bundleReq);
                bundleReq.Dispose();
            }
            else
            {
                if (LogMessages)
                {
                    Debug.Log($"Reloaded Bundle Cached for later use {bundleName}");
                }
                //store request for laster use
                loadedBundle.RequestForReload = bundleReq;
            }
        }
Esempio n. 4
0
    IEnumerator Start()
    {
        UnityWebRequest www = UnityWebRequestAssetBundle.GetAssetBundle("http://d3u3zwu9bmcdht.cloudfront.net/" + modelName);

        // www.downloadHandler = new DownloadHandlerBuffer();
        yield return(www.SendWebRequest());

        Debug.Log("http://d3u3zwu9bmcdht.cloudfront.net/" + modelName);

        if (www.result != UnityWebRequest.Result.Success)
        {
            Debug.Log(www.error);
        }
        else
        {
            AssetBundle assetFile = DownloadHandlerAssetBundle.GetContent(www);
            if (assetFile == null)
            {
                Debug.Log("Asset Load Error");
            }
            AssetBundleRequest prefab = assetFile.LoadAssetAsync("DesignChair");
            yield return(prefab);

            modelObject = prefab.asset as GameObject;
        }


        //var assetFile = AssetBundle.LoadFromFile(Path.Combine(Application.streamingAssetsPath, "daechair"));
        //Debug.Log(Application.streamingAssetsPath + "/daechair");

        //if (assetFile == null)
        //{
        //    Debug.Log("Asset Load Error");
        //}
        //AssetBundleRequest prefab = assetFile.LoadAssetAsync("DesignChair");
        //yield return prefab;
        //GameObject modelObject = prefab.asset as GameObject;



        /**** init for .dae file ****/
        GameObject daeObject = Instantiate(modelObject);

        // 태그 설정을 위해선 해당 태그 이름을 먼저 만들어 줘야한다.
        // 만약 동적인 tag가 필요하다면 editor script가 필요하다.
        daeObject.transform.tag = "Model";

        // destroy camera obj
        Destroy(daeObject.transform.GetChild(0).gameObject);
        daeObject.AddComponent <SumMeshRenderer>();
    }
Esempio n. 5
0
    private IEnumerator GetAudioAssetBundle()
    {
        var request = UnityWebRequestAssetBundle.GetAssetBundle(UrlAssetBundleAudio);

        yield return(request.SendWebRequest());

        while (!request.isDone)
        {
            yield return(null);
        }

        StateRequest(request, ref _audioAssetBundle);
        yield return(null);
    }
Esempio n. 6
0
    /// <summary>
    /// 远程下载
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="resName"></param>
    /// <param name="url"></param>
    /// <returns></returns>
    private IEnumerator DownAB <T>(string resName, string url) where T : Object
    {
        UnityWebRequest unityWebRequest = UnityWebRequestAssetBundle.GetAssetBundle(url);

        yield return(unityWebRequest.SendWebRequest());

        //AssetBundle assetBundle = DownloadHandlerAssetBundle.GetContent(unityWebRequest);
        AssetBundle assetBundle = (unityWebRequest.downloadHandler as DownloadHandlerAssetBundle).assetBundle;

        Debug.LogError(assetBundle == null);
        T gameObject = assetBundle.LoadAsset <T>(resName);

        Instantiate(gameObject, Camera.main.transform);
    }
    //public void DownloadAssetBundles(System.Action<string> action)
    //{
    //    if (unityAssets != null && unityAssets.Count > 0)
    //    {
    //        assetsCount = 0;

    //        foreach (KeyValuePair<string, string> bundle in unityAssets)
    //        {
    //            //StartCoroutine(LoadBundle(bundle.Key,action));

    //            StartCoroutine(LoadBundle(bundle.Key, (string s) =>
    //            {
    //                assetsCount++;

    //                action?.Invoke(s);
    //            }));
    //        }
    //    }
    //}

    public IEnumerator LoadBundle(string bundleName, System.Action <string> action)
    {
        if (!IsBundleLoaded(bundleName))
        {
            string url = unityAssets[bundleName];

            using (UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(url))
            {
                yield return(request.SendWebRequest());

                if (request.isNetworkError || request.isHttpError)
                {
                    Debug.Log("Code : " + request.responseCode);

                    if (request.responseCode >= 400)
                    {
                        action.Invoke(NoInterenet);
                    }
                    else if (request.responseCode >= 500)
                    {
                        action.Invoke(ServerError);
                    }
                    else
                    {
                        action.Invoke(NoInterenet);
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(request.error))
                    {
                        AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(request);

                        if (bundle != null)
                        {
                            assetBundles.Add(bundleName, bundle);

                            action.Invoke(Success);
                        }
                        else
                        {
                            Debug.Log("...." + request.error);

                            Debug.Log(request.downloadHandler.text);
                        }
                    }
                }
            }
        }
    }
Esempio n. 8
0
    /// <summary>
    /// 从服务器加载
    /// </summary>
    /// <param name="path"></param>
    private void ABLoadFromWeb(string path)
    {
        var uwr = UnityWebRequestAssetBundle.GetAssetBundle(path);

        uwr.SendWebRequest();
        //获得资源并实例化
        AssetBundle bundleWeb      = DownloadHandlerAssetBundle.GetContent(uwr);
        var         loadAsset      = bundleWeb.LoadAsset <GameObject>("Assets/Players/MainPlayer.prefab");
        var         loadAssetAsync = bundleWeb.LoadAssetAsync <GameObject>("Assets/Players/MainPlayer.prefab");

        Instantiate(loadAsset);
        Instantiate(loadAssetAsync.asset);
        bundleWeb.Unload(false);
    }
Esempio n. 9
0
    IEnumerator LoadAsset()
    {
        UnityWebRequest uwr = UnityWebRequestAssetBundle.GetAssetBundle("http://192.168.3.6:8998/Assetbundle/p");

        yield return(uwr.SendWebRequest());

        AssetBundle bundle    = DownloadHandlerAssetBundle.GetContent(uwr);
        var         loadAsset = bundle.LoadAssetAsync <GameObject>("Assets/Image/p.prefab");

        yield return(loadAsset);

        Debug.Log(loadAsset.asset.name);
        Instantiate(loadAsset.asset);
    }
Esempio n. 10
0
        /// <summary>
        /// Creates an asyncronous operation optimized for downloading a <see cref="AssetBundle"/> via HTTP GET.
        /// </summary>
        /// <param name="url">The URI of the asset bundle to download.</param>
        /// <param name="hash">A version hash. If this hash does not match the hash for the cached version of this asset bundle, the asset bundle will be redownloaded.</param>
        /// <param name="crc">If nonzero, this number will be compared to the checksum of the downloaded asset bundle data. If the CRCs do not match, an error will be logged and the asset bundle will not be loaded. If set to zero, CRC checking will be skipped.</param>
        /// <param name="userState">User-defined data.</param>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="url"/> is <see langword="null"/>.</exception>
        /// <exception cref="ArgumentException">Thrown if <paramref name="url"/> is an empty string.</exception>
        /// <returns>An operation that can be used to track the download process.</returns>
        /// <seealso cref="GetAssetBundleAsync(string, object)"/>
        public static IAsyncOperation <AssetBundle> GetAssetBundleAsync(string url, Hash128 hash, uint crc, object userState = null)
        {
            ThrowIfInvalidUrl(url);

#if UNITY_2018_1_OR_NEWER
            var webRequest = UnityWebRequestAssetBundle.GetAssetBundle(url, hash, crc);
#else
            var webRequest = UnityWebRequest.GetAssetBundle(url, hash, crc);
#endif

            var result = new Helpers.WebRequestResult <AssetBundle>(webRequest, userState);
            result.Start();
            return(result);
        }
Esempio n. 11
0
        /// <summary>
        /// Creates an asyncronous operation optimized for downloading scenes from <see cref="AssetBundle"/> via HTTP GET.
        /// </summary>
        /// <param name="url">The URI of the asset bundle to download.</param>
        /// <param name="hash">A version hash. If this hash does not match the hash for the cached version of this asset bundle, the asset bundle will be redownloaded.</param>
        /// <param name="crc">If nonzero, this number will be compared to the checksum of the downloaded asset bundle data. If the CRCs do not match, an error will be logged and the asset bundle will not be loaded. If set to zero, CRC checking will be skipped.</param>
        /// <param name="sceneName">Name of the prefab to load.</param>
        /// <param name="loadMode">Scene load mode.</param>
        /// <param name="userState">User-defined data.</param>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="url"/> is <see langword="null"/>.</exception>
        /// <exception cref="ArgumentException">Thrown if <paramref name="url"/> is an empty string.</exception>
        /// <returns>An operation that can be used to track the download process.</returns>
        /// <seealso cref="GetAssetBundleSceneAsync(string, string, LoadSceneMode, object)"/>
        public static IAsyncOperation <Scene> GetAssetBundleSceneAsync(string url, Hash128 hash, uint crc, string sceneName, LoadSceneMode loadMode, object userState = null)
        {
            ThrowIfInvalidUrl(url);

#if UNITY_2018_1_OR_NEWER
            var webRequest = UnityWebRequestAssetBundle.GetAssetBundle(url, hash, crc);
#else
            var webRequest = UnityWebRequest.GetAssetBundle(url, hash, crc);
#endif

            var result = new Helpers.AssetBundleLoadSceneResult(webRequest, sceneName, loadMode, userState);
            result.Start();
            return(result);
        }
Esempio n. 12
0
        /// <summary>
        /// Creates an asyncronous operation optimized for downloading assets from <see cref="AssetBundle"/> via HTTP GET.
        /// </summary>
        /// <param name="url">The URI of the asset bundle to download.</param>
        /// <param name="hash">A version hash. If this hash does not match the hash for the cached version of this asset bundle, the asset bundle will be redownloaded.</param>
        /// <param name="crc">If nonzero, this number will be compared to the checksum of the downloaded asset bundle data. If the CRCs do not match, an error will be logged and the asset bundle will not be loaded. If set to zero, CRC checking will be skipped.</param>
        /// <param name="assetName">Name of the prefab to load. If <see langword="null"/> the first asset of the matching type is loaded.</param>
        /// <param name="userState">User-defined data.</param>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="url"/> is <see langword="null"/>.</exception>
        /// <exception cref="ArgumentException">Thrown if <paramref name="url"/> is an empty string.</exception>
        /// <returns>An operation that can be used to track the download process.</returns>
        /// <seealso cref="GetAssetBundleAssetAsync(string, string, object)"/>
        public static IAsyncOperation <T> GetAssetBundleAssetAsync <T>(string url, Hash128 hash, uint crc, string assetName, object userState = null) where T : UnityEngine.Object
        {
            ThrowIfInvalidUrl(url);

#if UNITY_2018_1_OR_NEWER
            var webRequest = UnityWebRequestAssetBundle.GetAssetBundle(url, hash, crc);
#else
            var webRequest = UnityWebRequest.GetAssetBundle(url, hash, crc);
#endif

            var result = new Helpers.AssetBundleLoadAssetResult <T>(webRequest, assetName, userState);
            result.Start();
            return(result);
        }
Esempio n. 13
0
    //请求AB包
    IEnumerator InstantiateObject(string assetBundleName)
    {
        string          uri     = "file:///" + Application.dataPath + "/AssetBundles/" + assetBundleName;
        UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(uri, 0);

        yield return(request.SendWebRequest());

        AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(request);
        GameObject  cube   = bundle.LoadAsset <GameObject>("Cube");
        GameObject  sprite = bundle.LoadAsset <GameObject>("Sprite");

        Instantiate(cube);
        Instantiate(sprite);
    }
        private IEnumerator DownloadObjectData(GameObject obj, int vertexIndex, System.Action <string> callback)
        {
            yield return(new WaitUntil(() => pauseLoading == false));            //wait for opportunity to start

            pauseLoading = true;
            var meshFilter = obj.GetComponent <MeshFilter>();

            if (!meshFilter)
            {
                yield break;
            }

            string name     = meshFilter.mesh.name;
            string dataName = name.Replace(" Instance", "");

            dataName = dataName.Replace("mesh", "building");
            dataName = dataName.Replace("-", "_") + "-data";
            string dataURL = Config.activeConfiguration.buildingsMetaDataPath + dataName;

            ObjectMappingClass data;
            string             id = "null";

            using (UnityWebRequest uwr = UnityWebRequestAssetBundle.GetAssetBundle(dataURL))
            {
                yield return(uwr.SendWebRequest());

                if (uwr.isNetworkError || uwr.isHttpError)
                {
                    //Not showing warnings for now, because this can occur pretty often. I dialog would be annoying.
                    //WarningDialogs.Instance.ShowNewDialog("De metadata voor " + obj.name + " kon niet worden geladen. Ben je nog online?");
                }
                else if (obj != null)
                {
                    ObjectData  objectMapping  = obj.AddComponent <ObjectData>();
                    AssetBundle newAssetBundle = DownloadHandlerAssetBundle.GetContent(uwr);
                    data = newAssetBundle.LoadAllAssets <ObjectMappingClass>()[0];
                    int idIndex = data.vectorMap[vertexIndex];
                    id = data.ids[idIndex];
                    objectMapping.ids       = data.ids;
                    objectMapping.uvs       = data.uvs;
                    objectMapping.vectorMap = data.vectorMap;

                    newAssetBundle.Unload(true);
                }
            }
            callback?.Invoke(id);
            yield return(null);

            pauseLoading = false;
        }
Esempio n. 15
0
    IEnumerator LoadAsset()
    {
        modelManager.loadingBunles.Add(ABName);

#if UNITY_IOS
        BundleFullURL = PlayerPrefs.GetString("ApiUrl") + "/media/3d/" + ABName + "/ios/bundle";
#endif
#if PLATFORM_ANDROID
        BundleFullURL = PlayerPrefs.GetString("ApiUrl") + "/media/3d/" + ABName + "/android/bundle";
#endif
        Debug.Log("Load bundle by: " + BundleFullURL);

        CachedAssetBundle cab = new CachedAssetBundle(ABName, new Hash128(0, 0));
        using (UnityWebRequest uwr = UnityWebRequestAssetBundle.GetAssetBundle(BundleFullURL, cab))
        {
            preloader.LoadPercent(uwr);
            yield return(uwr.SendWebRequest());

            if (uwr.isNetworkError || uwr.isHttpError)
            {
                Debug.Log(uwr.error);
                preloader.CantLoad();
                preloader.Loaded();
                GetComponent <Collider>().enabled = false;
                GetComponent <Mover>().enabled    = false;
            }
            else
            {
                // Get downloaded asset bundle
                AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(uwr);
                if (bundle.Contains(AssetName))
                {
                    Instantiate(bundle.LoadAssetAsync(AssetName).asset, gameObject.transform);
                    modelManager.bundles.Add(bundle);
                    modelManager.loadingBunles.Remove(ABName);
                    mover.modelName = ABName;
                    Debug.Log("is OBJ");
                    preloader.Loaded();
                }
                else
                {
                    Debug.Log("Check !loaded Asset name: " + AssetName);
                    preloader.CantLoad();
                    preloader.Loaded();
                    GetComponent <Collider>().enabled = false;
                    GetComponent <Mover>().enabled    = false;
                }
            }
        }
    }
        private IEnumerator DownloadIDMappingData(TileChange tileChange, GameObject newGameobject, System.Action <TileChange> callback = null)
        {
            Tile       tile             = tiles[new Vector2Int(tileChange.X, tileChange.Y)];
            ObjectData oldObjectMapping = tile.gameObject.GetComponent <ObjectData>();
            GameObject newTile          = newGameobject;
            string     name             = newTile.GetComponent <MeshFilter>().mesh.name;

            Debug.Log(name);
            string dataName = name.Replace(" Instance", "");

            dataName = dataName.Replace("mesh", "building");
            dataName = dataName.Replace("-", "_") + "-data";
            string dataURL = Config.activeConfiguration.buildingsMetaDataPath + dataName;

            Debug.Log(dataURL);
            ObjectMappingClass data;

            using (UnityWebRequest uwr = UnityWebRequestAssetBundle.GetAssetBundle(dataURL))
            {
                yield return(uwr.SendWebRequest());

                if (uwr.isNetworkError || uwr.isHttpError)
                {
                    callback(tileChange);
                }
                else
                {
                    ObjectData  objectMapping  = newTile.AddComponent <ObjectData>();
                    AssetBundle newAssetBundle = DownloadHandlerAssetBundle.GetContent(uwr);
                    data = newAssetBundle.LoadAllAssets <ObjectMappingClass>()[0];

                    objectMapping.highlightIDs = oldObjectMapping.highlightIDs;
                    objectMapping.hideIDs      = oldObjectMapping.hideIDs;
                    objectMapping.ids          = data.ids;
                    objectMapping.uvs          = data.uvs;
                    objectMapping.vectorMap    = data.vectorMap;
                    objectMapping.mesh         = newTile.GetComponent <MeshFilter>().sharedMesh;
                    objectMapping.ApplyDataToIDsTexture();
                    newAssetBundle.Unload(true);
                }
            }
            yield return(new WaitUntil(() => pauseLoading == false));

            RemoveGameObjectFromTile(tileChange);
            tiles[new Vector2Int(tileChange.X, tileChange.Y)].gameObject = newGameobject;

            yield return(null);

            callback(tileChange);
        }
        private IEnumerator DownloadAssetBundle(TileChange tileChange, System.Action <TileChange> callback = null)
        {
            var    tileKey = new Vector2Int(tileChange.X, tileChange.Y);
            int    lod     = tiles[tileKey].LOD;
            string url     = Config.activeConfiguration.webserverRootPath + Datasets[lod].path;

            if (Datasets[lod].path.StartsWith("https://") || Datasets[lod].path.StartsWith("file://"))
            {
                url = Datasets[lod].path;
            }

            url = url.ReplaceXY(tileChange.X, tileChange.Y);
            var webRequest = UnityWebRequestAssetBundle.GetAssetBundle(url);

            tiles[tileKey].runningWebRequest = webRequest;
            yield return(webRequest.SendWebRequest());

            tiles[tileKey].runningWebRequest = null;

            if (webRequest.isNetworkError || webRequest.isHttpError)
            {
                RemoveGameObjectFromTile(tileKey);
                callback(tileChange);
            }
            else
            {
                AssetBundle assetBundle = DownloadHandlerAssetBundle.GetContent(webRequest);
                tiles[tileKey].assetBundle = assetBundle;
                yield return(new WaitUntil(() => pauseLoading == false));

                GameObject newGameobject = CreateNewGameObject(assetBundle, tileChange);
                if (newGameobject != null)
                {
                    if (TileHasHighlight(tileChange))
                    {
                        yield return(UpdateObjectIDMapping(tileChange, newGameobject, callback));
                    }
                    else
                    {
                        RemoveGameObjectFromTile(tileKey);
                        tiles[tileKey].gameObject = newGameobject;
                        callback(tileChange);
                    }
                }
                else
                {
                    callback(tileChange);
                }
            }
        }
Esempio n. 18
0
        private static AsyncOperation StartAssetBundleDownload(string assetBundleUrl, out UnityWebRequest webRequest)
        {
#if UNITY_2018_1_OR_NEWER
            webRequest = UnityWebRequestAssetBundle.GetAssetBundle(assetBundleUrl);
#else
            webRequest = UnityWebRequest.GetAssetBundle(assetBundleUrl);
#endif

#if UNITY_2017_2_OR_NEWER
            return(webRequest.SendWebRequest());
#else
            return(webRequest.Send());
#endif
        }
Esempio n. 19
0
        internal UnityWebRequest CreateWebRequest(IResourceLocation loc)
        {
            var url = m_ProvideHandle.ResourceManager.TransformInternalId(loc);

            if (m_Options == null)
            {
                return(UnityWebRequestAssetBundle.GetAssetBundle(url));
            }
            UnityWebRequest webRequest;

            if (!string.IsNullOrEmpty(m_Options.Hash))
            {
                CachedAssetBundle cachedBundle = new CachedAssetBundle(m_Options.BundleName, Hash128.Parse(m_Options.Hash));
#if ENABLE_CACHING
                if (m_Options.UseCrcForCachedBundle || !Caching.IsVersionCached(cachedBundle))
                {
                    webRequest = UnityWebRequestAssetBundle.GetAssetBundle(url, cachedBundle, m_Options.Crc);
                }
                else
                {
                    webRequest = UnityWebRequestAssetBundle.GetAssetBundle(url, cachedBundle);
                }
#else
                webRequest = UnityWebRequestAssetBundle.GetAssetBundle(url, cachedBundle, m_Options.Crc);
#endif
            }
            else
            {
                webRequest = UnityWebRequestAssetBundle.GetAssetBundle(url, m_Options.Crc);
            }

            if (m_Options.Timeout > 0)
            {
                webRequest.timeout = m_Options.Timeout;
            }
            if (m_Options.RedirectLimit > 0)
            {
                webRequest.redirectLimit = m_Options.RedirectLimit;
            }
#if !UNITY_2019_3_OR_NEWER
            webRequest.chunkedTransfer = m_Options.ChunkedTransfer;
#endif
            if (m_ProvideHandle.ResourceManager.CertificateHandlerInstance != null)
            {
                webRequest.certificateHandler = m_ProvideHandle.ResourceManager.CertificateHandlerInstance;
                webRequest.disposeCertificateHandlerOnDispose = false;
            }
            return(webRequest);
        }
Esempio n. 20
0
        private IEnumerator GetAssetBundle()
        {
            using (var uwr = UnityWebRequestAssetBundle.GetAssetBundle(this.assetUrl)) {
                Debug.Log("Prepare downloading...");

                var operation = uwr.SendWebRequest();

                // Computed percents
                while (!operation.isDone)
                {
                    var downloadDataProgress = uwr.downloadProgress * 112;
                    var currentPercent       = (int)downloadDataProgress;

                    if (downloadDataProgress > 0 && this.previousPercent != currentPercent)
                    {
                        this.previousPercent = currentPercent;
                        Debug.Log("Download: " + currentPercent + "%");
                    }
                    yield return(null);
                }

                if (uwr.isNetworkError || uwr.isHttpError)
                {
                    Debug.Log("Net error: " + uwr.error);
                }
                else
                {
                    this.bundle = DownloadHandlerAssetBundle.GetContent(uwr);
                    var scenePath = this.bundle.GetAllScenePaths();

                    // World
                    if (scenePath.Length > 0)
                    {
                        Debug.Log("Loading world...");
                        SceneManager.LoadScene(scenePath[0]);
                        Debug.Log("Successful!");
                        yield return(null);
                    }

                    // Avatar
                    {
                        Debug.Log("Loading avatar...");
                        var avatar = this.bundle.LoadAsset("_CustomAvatar.prefab");
                        Instantiate(avatar, new Vector3(0, 0, 0), Quaternion.identity);
                        Debug.Log("Successful!");
                    }
                }
            }
        }
Esempio n. 21
0
        public override void Start()
        {
            base.Start();

            if (m_UnityWebRequest != null)
            {
                m_UnityWebRequest.Dispose();
                m_UnityWebRequest = null;
            }

            bool   isCache = false;
            string path    = ResourceManager.instance.GetResourcePath(this.path, ref isCache, async);

            if (async)
            {
                string pathDst = FileUtil.GetAssetBundleFullPath(path);
                m_UnityWebRequest = UnityWebRequestAssetBundle.GetAssetBundle(pathDst, FileUtil.DefaultHash);
            }
            else
            {
                if (isCache)
                {
                    AssetBundle assetbundle = AssetBundle.LoadFromFile(path);
                    OnComplete(assetbundle);
                }
                else
                {
                    // FGUI有bug.造成LoginPanel适配有问题.临时处理,先去掉UI的缓存
                    string pathDst = path;
                    if (!path.StartsWith("ui/"))
                    {
                        string filename = System.IO.Path.GetFileNameWithoutExtension(path);
                        pathDst = FileUtil.GetCacheAssetBundlePath(filename);
                        if (!File.Exists(pathDst))
                        {
                            // 不存在,读取源文本
                            pathDst = path;

                            // 加到后台解压
                            path = FileUtil.GetAssetBundleFullPath(path);
                            ResourceManager.instance.AddToDownloadOrCache(path);
                        }
                    }

                    AssetBundle assetbundle = AssetBundle.LoadFromFile(pathDst);
                    OnComplete(assetbundle);
                }
            }
        }
    private IEnumerator Start()
    {
        //AssetBundle ab = AssetBundle.LoadFromFile("AssetBundles/wall.ab");

        string          uri     = @"http://localhost/AssetBundles/cubewall.unity3d";
        UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(uri);

        yield return(request.SendWebRequest());

        AssetBundle ab = DownloadHandlerAssetBundle.GetContent(request);

        GameObject wallPrefab = ab.LoadAsset <GameObject>("CubeWall");

        Instantiate(wallPrefab);
    }
    // it must wait for the web call to occur
    IEnumerator Start()
    {
        var unityWebRequestAB = UnityWebRequestAssetBundle.GetAssetBundle(fallbackAssetBundleurl);

        //use yield as it can take sometime for the web request to occur depending on the internet connection - wait for that to happen
        yield return(unityWebRequestAB.SendWebRequest());

        AssetBundle bundle    = DownloadHandlerAssetBundle.GetContent(unityWebRequestAB);
        var         loadAsset = bundle.LoadAssetAsync(prefabName);

        //make asset load in sync with start so the program is not stuck during waiting if it's got other things to do
        yield return(loadAsset);

        Instantiate(loadAsset.asset);
    }
Esempio n. 24
0
    public IEnumerator DownloadAssetBundle(string bundleUrl)
    {
        UnityWebRequest www = UnityWebRequestAssetBundle.GetAssetBundle(bundleUrl);

        yield return(www.SendWebRequest());

        if (www.isNetworkError || www.isHttpError)
        {
            Debug.Log(www.error);
        }
        else
        {
            //bundle is cached
        }
    }
Esempio n. 25
0
    IEnumerator LoadDefaultSabers()
    {
        var path = Path.Combine(Application.streamingAssetsPath, "sabers_default");

#if UNITY_ANDROID
        var uwr = UnityWebRequestAssetBundle.GetAssetBundle(path);
        yield return(uwr.SendWebRequest());

        var bundle = DownloadHandlerAssetBundle.GetContent(uwr);
        TryLoadSaberBundle(bundle);
#else
        TryLoadSaberBundle(AssetBundle.LoadFromFile(path));
        yield return(null);
#endif
    }
Esempio n. 26
0
        /// <summary>
        /// 加载依赖清单
        /// </summary>
        /// <returns></returns>
        public IEnumerator ManifestLoad()
        {
            UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(_loadPath);

            yield return(request.SendWebRequest());

            _manifestBundle = (request.downloadHandler as DownloadHandlerAssetBundle).assetBundle;
            if (_manifestBundle == null)
            {
                Debug.LogError(GetType() + "读取manifest失败:" + _loadPath);
                yield return(null);
            }
            _manifest     = _manifestBundle.LoadAsset(AssetBundleDefined.ASSETBUNDLE_MANIFEST_STR) as AssetBundleManifest;
            _isLoadFinish = true;
        }
    public IEnumerator DownloadAssetBundle(string url, downloadAssetBundleCallback cbk)
    {
        Debug.Log("下载AssetBundle: " + url);
        var uwr = UnityWebRequestAssetBundle.GetAssetBundle(url);

        yield return(uwr.SendWebRequest());

        // Get an asset from the bundle.
        AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(uwr);

        yield return(bundle);

        Debug.Log("下载完成.");
        cbk(bundle);
    }
 private void Update()
 {
     if (Input.GetKeyDown(KeyCode.Space))
     {
         destoryModel();
         Debug.Log("重新加载");
         //重新加载
         loadingBarSlider.gameObject.SetActive(true);
         //WWW www = new WWW(url);
         //addCoroutineList(StartCoroutine(showProgressAndLoadModel(www, scale)));
         StartCoroutine(showProgressAndLoadModel(UnityWebRequestAssetBundle.GetAssetBundle(url), Vector3.one));
         //WWW www1 = new WWW(url);
         //addCoroutineList(StartCoroutine(showProgressAndLoadModel1(www1, scale)));
     }
 }
Esempio n. 29
0
    IEnumerator DownloadAssets(string assetName, Vector3 pos)
    {
        DateTime        start   = DateTime.UtcNow;
        string          url     = "http://vcm-12481.vm.duke.edu/static/" + assetName;
        UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(url, 0);

        yield return(request.SendWebRequest());

        AssetBundle bundle   = DownloadHandlerAssetBundle.GetContent(request);
        TimeSpan    timeDiff = DateTime.UtcNow - start;

        Debug.Log("Downloading" + assetName + "takes" + Convert.ToInt32(timeDiff.TotalMilliseconds));

        _assetBundles.Add(new Tuple <string, Vector3, AssetBundle>(assetName, pos, bundle));
    }
Esempio n. 30
0
    //coroutine to get assetbundle from webserver
    IEnumerator GetAssetBundle()
    {
        //web request to get assetbundle from webserver, skips crc
        webRequest = UnityWebRequestAssetBundle.GetAssetBundle(assetBundleServerURL, 0);
        Debug.Log(webRequest == null ? "No web request" : "Web request exists");
        yield return(webRequest.SendWebRequest());

        //loads asset bundle
        ab = DownloadHandlerAssetBundle.GetContent(webRequest);
        Debug.Log(ab == null ? "Failed to load AssetBundle" : "Successfully Loaded AssetBundle");
        //instantiate object from assetbundle
        GameObject monkey = ab.LoadAsset <GameObject>("monkey_lp");

        Instantiate(monkey);
    }