public void Stop() { if (m_startLoad == true) { Addressables.Release(m_asyncHandle); } }
IEnumerator CheckUpdate() { SetState(EUpdateState.CheckUpdateCatalogs); var needUpdateCatalogs = false; var start = DateTime.Now; //开始连接服务器检查更新 checkHandle = Addressables.CheckForCatalogUpdates(false); //检查结束,验证结果 checkHandle.Completed += operationHandle => { if (checkHandle.Status == AsyncOperationStatus.Succeeded) { List <string> catalogs = checkHandle.Result; if (catalogs != null && catalogs.Count > 0) { needUpdateCatalogs = true; updateCatalogsList = catalogs; } } SetState(EUpdateState.AfterCheckCatalogs); }; yield return(checkHandle); Debug.Log($"CheckIfNeededUpdate({needUpdateCatalogs}) use {(DateTime.Now - start).Milliseconds} ms"); Addressables.Release(checkHandle); if (needUpdateCatalogs) { yield return(DownloadCatalogs()); } yield return(StartDownload()); }
private static void LoadGameObjectAsync <T>(string key, Action <UnityEngine.Object> cb) { AsyncOperationHandle handler = new AsyncOperationHandle(); if (mLoadedCbDict.ContainsKey(key) == false) { mLoadedCbDict[key] = new List <Action <UnityEngine.Object> >(); } mLoadedCbDict[key].Insert(0, cb); handler = Addressables.LoadAssetAsync <T>(key); handler.Completed += (AsyncOperationHandle loadedHandler) => { if (loadedHandler.Status == AsyncOperationStatus.Succeeded) { mAssetCacheDict[key] = loadedHandler; if (mLoadedCbDict.ContainsKey(key) == false) { Debug.LogError("资源加载完成,但回调已经清空" + key); Addressables.Release(handler); return; } int count = mLoadedCbDict[key].Count; for (int i = count - 1; i >= 0; i--) { mLoadedCbDict[key][i](loadedHandler.Result as UnityEngine.Object); } mLoadedCbDict[key].Clear(); } }; }
/// <summary> /// 下载指定资源 /// </summary> public static void DownloadAssets(IEnumerable keys) { var handle = Addressables.DownloadDependenciesAsync(keys, Addressables.MergeMode.Union); handle.WaitForCompletion(); if (handle.Status == AsyncOperationStatus.Succeeded) { Debug.Log("Download result type: " + handle.Result.GetType()); foreach (var item in handle.Result as List <IAssetBundleResource> ) { var ab = item.GetAssetBundle(); Debug.Log("AssetBundle name: " + ab.name); foreach (var assetName in ab.GetAllAssetNames()) { Debug.Log("Asset name: " + assetName); } } } else { Debug.Log("Download assets failed"); } Addressables.Release(handle); }
private static async Task <bool> AddAdditionalInfo(GameEntity entity, AsyncOperationHandle <GameObject> handle) { bool isStillValid = true; entity.OnDestroyEntity += entity1 => { isStillValid = false; }; GameObject resultObject = await handle.Task; if (!isStillValid) { Addressables.Release(handle); return(false); } if (entity != null && entity.isEnabled) { entity.AddAsyncOperationHandle(handle); entity.AddView(resultObject); entity.AddPosition(resultObject.transform.position); resultObject.Link(entity); } else { Addressables.Release(handle); } return(isStillValid); }
public IEnumerator SceneTests_Release_ReleaseNotRefCountZeroWhileLoadingDoesntUnloadAfterLoadCompletes() { // Setup var op = m_Addressables.LoadSceneAsync(sceneKeys[0], LoadSceneMode.Additive); Addressables.ResourceManager.Acquire(op); // Test op.Completed += s => Assert.IsTrue(SceneManager.GetSceneByName(sceneKeys[0]).isLoaded); Addressables.Release(op); yield return(op); Assert.IsTrue(SceneManager.GetSceneByName(sceneKeys[0]).isLoaded); Assert.IsTrue(op.IsValid()); // Cleanup yield return(op); Assert.IsTrue(SceneManager.GetSceneByName(sceneKeys[0]).isLoaded); Assert.IsTrue(op.IsValid()); m_Addressables.Release(op); yield return(op); Assert.IsFalse(SceneManager.GetSceneByName(sceneKeys[0]).isLoaded); Assert.IsFalse(op.IsValid()); }
/// <summary> /// Abort asynchronous loading /// </summary> public void Abort() { if (audioAsset == null) { return; } if (audioAsset.status != RB.AssetStatus.Loading) { return; } if (mResourceRequest != null) { // Can't abort a ResourceRequest... we will just ignore it mResourceRequest = null; } if (mWebRequest != null) { mWebRequest.Dispose(); mWebRequest = null; } #if ADDRESSABLES_PACKAGE_AVAILABLE Addressables.Release(mAddressableRequest); mAddressableRequest = new AsyncOperationHandle <AudioClip>(); #endif }
public override void OnDispose() { foreach (var asset in LoadedAssets) { Addressables.Release(asset.Value); } }
/// <summary> /// Abort asynchronous loading /// </summary> public void Abort() { if (spriteSheetAsset == null) { return; } if (spriteSheetAsset.status != RB.AssetStatus.Loading) { return; } if (mResourceRequest != null) { // Can't abort a ResourceRequest... we will just ignore it mResourceRequest = null; } if (mWebRequest != null) { mWebRequest.Dispose(); mWebRequest = null; } #if ADDRESSABLES_PACKAGE_AVAILABLE Addressables.Release(mAddressableRequestInfo); mAddressableRequestInfo = new AsyncOperationHandle <TextAsset>(); Addressables.Release(mAddressableRequestTexture); mAddressableRequestTexture = new AsyncOperationHandle <Texture2D>(); #endif }
IEnumerator InitAppVersion() { AsyncOperationHandle <TextAsset> handle = Addressables.LoadAssetAsync <TextAsset>(BuildUtils.AppVersionFileName); yield return(handle); if (handle.Status == AsyncOperationStatus.Succeeded) { var streamingAppVersion = handle.Result.text; var appVersionPath = AssetBundleUtility.GetPersistentDataPath(BuildUtils.AppVersionFileName); var persistentAppVersion = GameUtility.SafeReadAllText(appVersionPath); Logger.Log(string.Format("streamingAppVersion = {0}, persistentAppVersion = {1}", streamingAppVersion, persistentAppVersion)); // 如果persistent目录版本比streamingAssets目录app版本低,说明是大版本覆盖安装,清理过时的缓存 if (!string.IsNullOrEmpty(persistentAppVersion) && BuildUtils.CheckIsNewVersion(persistentAppVersion, streamingAppVersion)) { var path = AssetBundleUtility.GetPersistentDataPath(); GameUtility.SafeDeleteDir(path); } GameUtility.SafeWriteAllText(appVersionPath, streamingAppVersion); ChannelManager.instance.appVersion = streamingAppVersion; Addressables.Release(handle); } yield break; }
private void OnDestroy() { while (asyncOperationHandleQueues.Count > 0) { Addressables.Release(asyncOperationHandleQueues.Dequeue()); } }
private void CacheObjectInDictionary(string assetName, Action <GameObject> callback) { IResourceLocation location; if (_cachedAddressableLocations.TryGetValue(assetName, out location)) { AsyncOperationHandle <GameObject> asyncObj = Addressables.LoadAssetAsync <GameObject>(location); asyncObj.Completed += handle => { GameObject obj = handle.Result; if (obj == null) { Debug.LogError(string.Format("Unable to load {0} from {1} in AssetManager", assetName, location)); return; } Debug.Log("Loaded " + obj.name); _cachedPrefabDictionary.Add(obj.name, obj); callback(obj); Addressables.Release(asyncObj); }; } else { Debug.LogError(string.Format("Cannot find {0} in cachedAddressableLocations", assetName)); } }
private void CacheSpriteInDictionary(string assetName, Action <Sprite> callback) { IResourceLocation location; if (_cachedAddressableLocations.TryGetValue(assetName, out location)) { AsyncOperationHandle <UnityEngine.Object> asyncSprite = Addressables.LoadAssetAsync <UnityEngine.Object>(location); asyncSprite.Completed += handle => { Texture2D text = handle.Result as Texture2D; Sprite sprite = Sprite.Create(text, new Rect(0, 0, text.width, text.height), new Vector2(0.5f, 0.5f)); if (sprite == null) { Debug.LogError(string.Format("Unable to load {0} from {1} in AssetManager", assetName, location)); return; } Debug.Log("Loaded " + text.name); _cachedSpriteDictionary.Add(text.name, sprite); callback(sprite); Addressables.Release(asyncSprite); }; } else { Debug.LogError(string.Format("Cannot find {0} in cachedAddressableLocations", assetName)); } }
IEnumerator checkUpdate() { //初始化Addressable var init = Addressables.InitializeAsync(); yield return(init); //开始连接服务器检查更新 AsyncOperationHandle <List <string> > checkHandle = Addressables.CheckForCatalogUpdates(false); //检查结束,验证结果 yield return(checkHandle); if (checkHandle.Status == AsyncOperationStatus.Succeeded) { List <string> catalogs = checkHandle.Result; if (catalogs != null && catalogs.Count > 0) { Debug.Log("download start"); var updateHandle = Addressables.UpdateCatalogs(catalogs, false); yield return(updateHandle); Debug.Log("download finish"); } } Addressables.Release(checkHandle); }
protected override async void Execute(List <GameEntity> entities) { foreach (GameEntity levelEntity in entities) { if (levelEntity.hasAsyncOperationHandle) { Addressables.Release(levelEntity.asyncOperationHandle.Value); levelEntity.RemoveAsyncOperationHandle(); } if (levelEntity.hasView) { levelEntity.view.Value.Unlink(); GameObject.Destroy(levelEntity.view.Value); levelEntity.RemoveView(); } } GameEntity[] tempList = entities.ToArray(); foreach (GameEntity levelEntity in tempList) { AssetReference levelReference = GameConfigurations.AssetReferenceConfiguration.LevelAssetReferences[levelEntity.levelIndex.Value]; await AssetLoaderUtils.InstantiateAssetAsyncTask(levelReference, levelEntity, Vector3.zero, Quaternion.identity); } }
IEnumerator UpdateCatalogs() { AsyncOperationHandle<List<IResourceLocator>> updateHandle = Addressables.UpdateCatalogs(); yield return updateHandle; Addressables.Release(updateHandle); }
public IEnumerator DownAssetImpl() { var downloadsize = Addressables.GetDownloadSizeAsync((IEnumerable)_updateKeys); yield return(downloadsize); Debug.Log("start download size :" + downloadsize.Result); DownloadPercent.text = "start download size :" + downloadsize.Result; if (downloadsize.Result > 0) { _isDownloading = true; _downloadHandle = Addressables.DownloadDependenciesAsync((IEnumerable)_updateKeys, Addressables.MergeMode.Union); yield return(_downloadHandle); //await download.Task; Debug.Log("download result type " + _downloadHandle.Result.GetType()); foreach (var item in _downloadHandle.Result as List <UnityEngine.ResourceManagement.ResourceProviders.IAssetBundleResource> ) { var ab = item.GetAssetBundle(); foreach (var name in ab.GetAllAssetNames()) { Debug.Log("asset name " + name); } } Addressables.Release(_downloadHandle); } _isDownloading = false; Addressables.Release(downloadsize); }
private IEnumerator PreloadHazards() { //find all the locations with label "SpaceHazards" var loadResourceLocationsHandle = Addressables.LoadResourceLocationsAsync("SpaceHazards", typeof(GameObject)); if (!loadResourceLocationsHandle.IsDone) yield return loadResourceLocationsHandle; //start each location loading List<AsyncOperationHandle> opList = new List<AsyncOperationHandle>(); foreach (IResourceLocation location in loadResourceLocationsHandle.Result) { AsyncOperationHandle<GameObject> loadAssetHandle = Addressables.LoadAssetAsync<GameObject>(location); loadAssetHandle.Completed += obj => { _preloadedObjects.Add(location.PrimaryKey, obj.Result); }; opList.Add(loadAssetHandle); } //create a GroupOperation to wait on all the above loads at once. var groupOp = Addressables.ResourceManager.CreateGenericGroupOperation(opList); if (!groupOp.IsDone) yield return groupOp; Addressables.Release(loadResourceLocationsHandle); //take a gander at our results. foreach (var item in _preloadedObjects) { Debug.Log(item.Key + " - " + item.Value.name); } }
public IEnumerator DownAssetImpl() { var downloadsize = Addressables.GetDownloadSizeAsync(_updateKeys); yield return(downloadsize); Debug.Log("start download size :" + downloadsize.Result); if (downloadsize.Result > 0) { var download = Addressables.DownloadDependenciesAsync(_updateKeys, Addressables.MergeMode.Intersection); yield return(download); //await download.Task; Debug.Log("download result type " + download.Result.GetType()); foreach (var item in download.Result as List <UnityEngine.ResourceManagement.ResourceProviders.IAssetBundleResource> ) { var ab = item.GetAssetBundle(); Debug.Log("ab name " + ab.name); foreach (var name in ab.GetAllAssetNames()) { Debug.Log("asset name " + name); } } Addressables.Release(download); } Addressables.Release(downloadsize); }
//检查catalog的更新 public ETTask <string> CheckForCatalogUpdates() { ETTask <string> result = ETTask <string> .Create(); var handle = Addressables.CheckForCatalogUpdates(false); handle.Completed += (res) => { if (handle.Status == AsyncOperationStatus.Succeeded) { if (handle.Result != null && handle.Result.Count > 0) { result.SetResult(handle.Result[0]); } else { Debug.LogError("handle.Result == null || handle.Result.Count == 0, Check catalog_1.hash is exist"); result.SetResult(null); } } else { Debug.LogError("handle.Status == AsyncOperationStatus.Succeeded"); result.SetResult(null); } Addressables.Release(handle); }; return(result); }
private void OnDestroy() { foreach (var item in operationDictionary) { Addressables.Release(item.Value); } }
public ResourceHandle LoadAsync <T>(string key, Action <IList <UnityEngine.Object> > callback) { var handle = new ResourceHandle(GenerateHandleId(), key, typeof(T)); Assert.IsTrue(!handle.IsSceneObject); m_HandleList.Add(handle); // キーが存在するかチェックした上でロード var locationHandle = Addressables.LoadResourceLocationsAsync(key); m_ResourceLocationHandleDict.Add(key, locationHandle); locationHandle.Completed += op => { // キーが存在するか var isExists = op.Status == AsyncOperationStatus.Succeeded && op.Result != null && 1 <= op.Result.Count; if (isExists) { // ロード handle.HandleAsssets = Addressables.LoadAssetsAsync <UnityEngine.Object>(key, null); handle.HandleAsssets.Completed += op2 => { if (op2.Status == AsyncOperationStatus.Succeeded) { #if UNITY_EDITOR Fwk.DebugSystem.Log.DebugUseResourceLog.Instance.Append("key:" + key); foreach (var obj in op2.Result) { Fwk.DebugSystem.Log.DebugUseResourceLog.Instance.Append("- " + obj.name); } #endif callback(op2.Result); } else { m_HandleList.Remove(handle); Debug.LogFormat("Status[{0}]: key => {1}", op2.Status, handle.Key); } if (op2.OperationException != null) { Debug.LogWarningFormat("Load is null => {0}", op2.OperationException.ToString()); } }; } else { m_HandleList.Remove(handle); Debug.LogFormat("[key => {0}] 指定キーのリソースがない可能性があります", handle.Key); Debug.Log("実機でのみここに入ってくる場合、Addressable Group のスキーマ設定を見直して下さい"); } // ResourceLocationHandle の後片付け AsyncOperationHandle <IList <IResourceLocation> > resultHandle; m_ResourceLocationHandleDict.TryGetValue(key, out resultHandle); m_ResourceLocationHandleDict.Remove(key); Addressables.Release(resultHandle); }; return(handle); }
public IEnumerator GetDialogueAsync(string key, Action <string> callback) { switch (sourceType) { case SourceType.Resources: var progress = Resources.LoadAsync <TextAsset>(Path.Combine(dialoguePath, key).Replace("\\", "/")); yield return(new WaitUntil(() => progress.isDone)); var ta = progress.asset as TextAsset; callback(ta.text); break; #if ADDRESSABLE_EXISTS case SourceType.Addressable: var finalPath = useFormatPath ? string.Format(dialoguePath, key) : Path.Combine(dialoguePath, key).Replace("\\", "/"); var progress3 = Addressables.LoadAssetAsync <TextAsset>(finalPath); yield return(new WaitUntil(() => progress3.IsDone)); callback(progress3.Result.text); Addressables.Release(progress3); break; #endif case SourceType.Custom: yield return(provider.GetDialogue(key, result => { callback(result); })); break; } }
private IEnumerator CalculateUpdateSizeAsync() { for (int i = 0; i < updateLocators.Count; i++) { IList <IResourceLocation> locations; var e = updateLocators[i].Keys.GetEnumerator(); while (e.MoveNext()) { if (updateLocators[i].Locate(e.Current, typeof(object), out locations)) { for (int j = 0; j < locations.Count; j++) { if (updateKeys.Contains(locations[j].PrimaryKey)) { continue; } updateKeys.Add(locations[j].PrimaryKey); } } } } var downloadSizeHandle = Addressables.GetDownloadSizeAsync(updateKeys); yield return(downloadSizeHandle); downloadSize = downloadSizeHandle.Result; Addressables.Release(downloadSizeHandle); }
public void RegisterButtonClick(GameObject go) { if (index % 2 == 1) { AsyncOperationHandle <SpriteAtlas> handle = Addressables.LoadAssetAsync <SpriteAtlas>("QTE"); // AsyncOperationHandle<Sprite[]> handle = Addressables.LoadAssetAsync<Sprite[]>(atlasName); handle.Completed += (op) => { if (op.Status == AsyncOperationStatus.Succeeded) { atlas = handle.Result; startButton.image.sprite = atlas.GetSprite("ui_button_001"); // if (!_cachedAtlasDict.ContainsKey(atlasName)) // _cachedAtlasDict.Add(atlasName, handle.Result); // image.sprite = _cachedAtlasDict[atlasName].GetSprite(imageName); } }; } else { Addressables.Release(atlas); } index++; return; // Debug.Log("Try Register! " + nameInput.text); // RegisterArgs args = new RegisterArgs(); // args.account = nameInput.text; // NetworkManager.RegisterReq(args, RegisterAck); }
private IEnumerator DownloadAsync() { long downloadedSize = 0; for (int i = 0; i < updateKeys.Count; i++) { var downloadSizeHandle = Addressables.GetDownloadSizeAsync(updateKeys[i]); yield return(downloadSizeHandle); long size = downloadSizeHandle.Result; Addressables.Release(downloadSizeHandle); if (size <= 0) { continue; } var downloadHandle = Addressables.DownloadDependenciesAsync(updateKeys[i]); while (downloadHandle.PercentComplete < 1 && !downloadHandle.IsDone) { OnDownload?.Invoke(downloadedSize + (long)(downloadHandle.PercentComplete * size), downloadSize); #if UNITY_EDITOR Debug.Log(string.Format("Download Size: {0}/{1}", downloadedSize + (long)(downloadHandle.PercentComplete * size), downloadSize)); #endif yield return(null); } downloadedSize += size; Addressables.Release(downloadHandle); if (downloadedSize >= downloadSize) { break; } } }
private void UnloadAsset(AssetData assetData) { if (!assetData.isKeep) { #if AssetBundle if (assetData.isAssetBundle) { #if !UNITY_EDITOR Addressables.Release(assetData.asset); #endif } else { if (assetData.asset.GetType() != typeof(GameObject) && assetData.asset.GetType() != typeof(Component)) { //Resources.UnloadAsset仅能释放非GameObject和Component的资源 比如Texture Mesh等真正的资源 对于由Prefab加载出来的Object或Component,则不能通过该函数来进行释放 Resources.UnloadAsset(assetData.asset); } } #else if (assetData.asset.GetType() != typeof(GameObject) && assetData.asset.GetType() != typeof(Component)) { //Resources.UnloadAsset仅能释放非GameObject和Component的资源 比如Texture Mesh等真正的资源 对于由Prefab加载出来的Object或Component,则不能通过该函数来进行释放 Resources.UnloadAsset(assetData.asset); } #endif } }
private IEnumerator UpdateResourceLocatorsAsync() { Addressables.ClearResourceLocators(); string[] catalogs = null; if (Directory.Exists(addressablesDir)) { catalogs = GetCatalogs(addressablesDir, "json", SearchOption.TopDirectoryOnly); for (int i = 0; i < catalogs.Length; i++) { var catalogHandle = Addressables.LoadContentCatalogAsync(catalogs[i]); yield return(catalogHandle); Addressables.AddResourceLocator(catalogHandle.Result); Addressables.Release(catalogHandle); } } if (catalogs == null || catalogs.Length == 0) { catalogs = GetCatalogs(Addressables.RuntimePath, "json", SearchOption.TopDirectoryOnly); for (int i = 0; i < catalogs.Length; i++) { var catalogHandle = Addressables.LoadContentCatalogAsync(catalogs[i]); yield return(catalogHandle); Addressables.AddResourceLocator(catalogHandle.Result); Addressables.Release(catalogHandle); } } }
public IEnumerator TestAssetReferenceTMethod() { yield return(ValidateTestDependency()); PreInstall(); Container.BindAsync <GameObject>() .FromAssetReferenceT(addressablePrefabReference) .AsCached(); PostInstall(); AddressableInject <GameObject> asyncPrefab = Container.Resolve <AddressableInject <GameObject> >(); int frameCounter = 0; while (!asyncPrefab.HasResult && !asyncPrefab.IsFaulted) { frameCounter++; if (frameCounter > 10000) { Assert.Fail(); } yield return(null); } Addressables.Release(asyncPrefab.AssetReferenceHandle); Assert.Pass(); }
void OnDisable() { var sprite = image.sprite; image.sprite = null; Addressables.Release(sprite); }