Exemplo n.º 1
0
        /// <summary>
        /// This method will load the custom scene and merge it in.
        /// </summary>
        private static IEnumerator MergeCustomScene(LevelInfo level)
        {
            // If we've already loaded the bundle, take it from the dict, otherwise load it.
            AssetBundle bundle;

            if (!LoadedBundles.ContainsKey(level.AssetBundlePath))
            {
                bundle = level.AssetBundle;
                LoadedBundles.Add(level.AssetBundlePath, bundle);
            }
            else
            {
                bundle = LoadedBundles[level.AssetBundlePath];
            }

            var sceneName = Path.GetFileNameWithoutExtension(bundle.GetAllScenePaths()[0]);

            // Let Unity load the custom scene
            SceneManager.LoadScene(sceneName, LoadSceneMode.Additive);
            yield return(null);

            // Then merge the scene into the original
            SceneManager.MergeScenes(SceneManager.GetSceneAt(SceneManager.sceneCount - 1), SceneManager.GetActiveScene());

            // Find the level component
            ObjectReferences.CustomScene = _loadedScene.GetRootGameObjects()
                                           .Single(x => x.name == "[TNHLEVEL]" || x.name == "[LEVEL]")
                                           .GetComponent <CustomScene>();
        }
 private void GetLoadedBundles()
 {
     LoadedBundles.Clear();
     foreach (var item in AssetBundleMagic.Bundles.Keys)
     {
         LoadedBundles.Add(item);
     }
 }
Exemplo n.º 3
0
    public async UniTask <AssetBundle> LoadCachedBundle(string bundleId)
    {
        if (LoadedBundles.ContainsKey(bundleId))
        {
            LoadedBundles[bundleId].RefCount++;
            return(LoadedBundles[bundleId].AssetBundle);
        }
        Debug.Log($"[BundleManager] Requested cached bundle {bundleId}");
        Debug.Log($"[BundleManager] Version: {Catalog.GetEntry(bundleId).version}");
        if (!IsCached(bundleId))
        {
            return(null);
        }
        UnityWebRequest request;

        if (IsUpToDate(bundleId))
        {
            Debug.Log($"[BundleManager] Cached bundle matches version");
            // Use latest version
            request = UnityWebRequestAssetBundle.GetAssetBundle(bundleId, Catalog.GetEntry(bundleId).version, 0U);
        }
        else
        {
            // Use any existing version
            var list = new List <Hash128>();
            Caching.GetCachedVersions(bundleId, list);
            Debug.Log($"[BundleManager] Cached bundle does not match version. Using {list.Last()}...");
            request = UnityWebRequestAssetBundle.GetAssetBundle(bundleId, list.Last());
        }
        using (request)
        {
            await request.SendWebRequest();

            if (request.isNetworkError || request.isHttpError)
            {
                Debug.LogError(request.error);
                return(null);
            }

            var ab = DownloadHandlerAssetBundle.GetContent(request);
            LoadedBundles[bundleId] = new Entry {
                Id = bundleId, AssetBundle = ab, RefCount = 1
            };
            return(ab);
        }
    }
Exemplo n.º 4
0
    public void Release(string bundleId, bool force = false)
    {
        if (bundleId == null)
        {
            throw new ArgumentNullException();
        }
        if (!LoadedBundles.ContainsKey(bundleId))
        {
            return;
        }
        var entry = LoadedBundles[bundleId];

        entry.RefCount--;
        if (entry.RefCount <= 0 || force)
        {
            if (entry.RefCount < 0)
            {
                Debug.LogError("RefCount < 0!");
            }
            entry.AssetBundle.Unload(true);
            LoadedBundles.Remove(bundleId);
        }
    }
Exemplo n.º 5
0
    public async UniTask <AssetBundle> LoadBundle(
        string bundleId,
        bool loadFromStreamingAssets,
        bool showDialog,
        bool allowAbort            = true,
        bool instantiate           = true,
        Action onDownloadSucceeded = default,
        Action onDownloadAborted   = default,
        Action onDownloadFailed    = default,
        Action onLocallyResolved   = default
        )
    {
        if (bundleId == null)
        {
            throw new ArgumentNullException(nameof(bundleId));
        }
        if (!loadFromStreamingAssets)
        {
            Debug.Log($"[BundleManager] Requested remote bundle {bundleId}");
        }
        else
        {
            Debug.Log($"[BundleManager] Requested StreamingAssets bundle {bundleId}");
        }
        Debug.Log($"[BundleManager] Version: {Catalog.GetEntry(bundleId).version}");

        if (!Catalog.ContainsEntry(bundleId))
        {
            Debug.LogError($"[BundleManager] {bundleId} does not exist in the catalog!");
            return(null);
        }

        if (onLocallyResolved == default)
        {
            onLocallyResolved = () => { }
        }
        ;
        if (onDownloadSucceeded == default)
        {
            onDownloadSucceeded = () => { }
        }
        ;
        if (onDownloadAborted == default)
        {
            onDownloadAborted = () => { }
        }
        ;
        if (onDownloadFailed == default)
        {
            onDownloadFailed = () => { }
        }
        ;

        if (IsCached(bundleId))
        {
            Debug.Log($"[BundleManager] Bundle is cached");

            if (IsUpToDate(bundleId))
            {
                Debug.Log($"[BundleManager] Cached bundle matches version");
                onLocallyResolved();

                if (!instantiate)
                {
                    return(null);
                }
                return(await LoadCachedBundle(bundleId));
            }
        }

        var downloadUrl = loadFromStreamingAssets ? BuiltInBundlesBasePath + bundleId : Context.BundleRemoteFullUrl + bundleId;

        Debug.Log($"[BundleManager] URL: {downloadUrl}");

        // Check download size
        var totalSize = 0ul;

        if (!loadFromStreamingAssets)
        {
            if (!Application.isEditor || !Context.Instance.editorUseLocalAssetBundles)
            {
                try
                {
                    using (var headRequest = UnityWebRequest.Head(downloadUrl))
                    {
                        await headRequest.SendWebRequest();

                        if (headRequest.isNetworkError || headRequest.isHttpError)
                        {
                            Debug.LogError(headRequest.error);
                            onDownloadFailed();
                            return(null);
                        }

                        totalSize = ulong.Parse(headRequest.GetResponseHeader("Content-Length"));
                        Debug.Log($"[BundleManager] Download size: {totalSize.ToHumanReadableFileSize()}");
                    }
                }
                catch (Exception e)
                {
                    Debug.LogError(e);
                    onDownloadFailed();
                    return(null);
                }
            }
            else
            {
                totalSize = 99999999;
            }
        }

        Dialog dialog  = null;
        var    request = UnityWebRequestAssetBundle.GetAssetBundle(downloadUrl, Catalog.GetEntry(bundleId).version, 0U);
        var    aborted = false;

        if (showDialog)
        {
            dialog                   = Dialog.Instantiate();
            dialog.Message           = "DIALOG_DOWNLOADING".Get();
            dialog.UseProgress       = true;
            dialog.UsePositiveButton = false;
            dialog.UseNegativeButton = allowAbort;
            dialog.onUpdate.AddListener(it =>
            {
                if (aborted)
                {
                    return;
                }
                var downloadedSize = request.downloadedBytes;
                it.Progress        = totalSize == 0 ? 0 : downloadedSize * 1.0f / totalSize;
                it.Message         = "DIALOG_DOWNLOADING_X_Y".Get(downloadedSize.ToHumanReadableFileSize(),
                                                                  totalSize.ToHumanReadableFileSize());
            });
            if (allowAbort)
            {
                dialog.OnNegativeButtonClicked = it =>
                {
                    dialog.Close();
                    aborted = true;
                };
            }

            dialog.Open();
        }

        using (request)
        {
            request.SendWebRequest();

            while (!request.isDone)
            {
                if (aborted)
                {
                    break;
                }
                await UniTask.Yield();
            }

            if (aborted)
            {
                request.Abort();
                onDownloadAborted();
                return(null);
            }

            if (request.isNetworkError || request.isHttpError)
            {
                Debug.LogError(request.error);
                onDownloadFailed();
                return(null);
            }

            if (showDialog)
            {
                dialog.Close();
            }

            onDownloadSucceeded();

            if (!instantiate)
            {
                return(null);
            }

            if (LoadedBundles.ContainsKey(bundleId))
            {
                Release(bundleId);
            }

            var ab = ((DownloadHandlerAssetBundle)request.downloadHandler).assetBundle;
            ab.GetAllAssetNames().ForEach(Debug.Log);
            LoadedBundles[bundleId] = new Entry {
                Id = bundleId, AssetBundle = ab, RefCount = 1
            };
            return(ab);
        }
    }