private async UniTask <List <IResourceLocation> > LoadAllLocations() { var task = ExtraLabels != null?Addressables.LoadResourceLocationsAsync(ExtraLabels, Addressables.MergeMode.Intersection) : Addressables.LoadResourceLocationsAsync(MainLabel); while (!task.IsDone) // When awaiting the method directly it fails on WebGL (they're using mutlithreaded Task fot GetAwaiter) { await AsyncUtils.WaitEndOfFrame; } var locations = task.Result; return(locations?.ToList() ?? new List <IResourceLocation>()); }
public async Task Test1() { var handle = Addressables.LoadResourceLocationsAsync("Sprite1"); await handle.Task; for (int i = 0; i < handle.Result.Count; i++) { IResourceLocation resourceLocation = handle.Result[i]; Debug.Log($"PrimaryKey:{resourceLocation.PrimaryKey}"); Debug.Log($"InternalId:{resourceLocation.InternalId}"); Debug.Log($"ProviderId:{resourceLocation.ProviderId}"); } }
public static IEnumerator CoCheckAtlasExist(string name, System.EventHandler <bool> onComplete) { string atlasAddress = GetAtlasAddressFromPictureName(name); AsyncOperationHandle <IList <IResourceLocation> > handle = Addressables.LoadResourceLocationsAsync(atlasAddress); yield return(handle); bool isExist = handle.Result.Count > 0; Debug.Log($"Atlas Exist: {isExist}"); onComplete?.Invoke(null, isExist); Addressables.Release(handle); yield return(isExist); }
/// <summary> /// Determines the clips and loads them into memory. This must be called first. /// </summary> public async void LoadAllClipsAsync() { addressableAssets = Addressables.LoadResourceLocationsAsync(labels, Addressables.MergeMode.Intersection); addressableAssets.Completed += AddressablesLoading_Completed; await addressableAssets.Task; List <System.Threading.Tasks.Task> clipLoadingTasks = new List <System.Threading.Tasks.Task>(assetHandles.Count); foreach (var handle in assetHandles) { clipLoadingTasks.Add(handle.Task); } await System.Threading.Tasks.Task.WhenAll(clipLoadingTasks); }
private void LoadMusicAddressesAsync(string musicGenre) { var addressableLabels = new List <string>() { "music" }; if (musicGenre != null && musicGenre != String.Empty) { addressableLabels.Add(musicGenre); } addressableAssets = Addressables.LoadResourceLocationsAsync(addressableLabels, Addressables.MergeMode.Intersection); addressableAssets.Completed += SaveClipAddresses; }
public static async Task <Sprite> GetSpriteFromAtlasAsync(string name) { FirebaseManager.CheckWaitForReady((object sender, bool success) => { if (success) { FirebaseManager.LogCrashlytics($"{Const.CRASHLYTIC_LOG_PICTURE}_{name}"); } }); //check if atlas exist string atlasAddress = GetAtlasAddressFromPictureName(name); AsyncOperationHandle <IList <IResourceLocation> > handle = Addressables.LoadResourceLocationsAsync(atlasAddress); await handle.Task; bool atlasExist = handle.Result.Count > 0; //.Log($"Atlas Exist: {atlasExist}"); Addressables.Release(handle); //if not, use OTHER atlas if (!atlasExist) { atlasAddress = GetAtlasAddressFromPictureName("OTHER"); } //return sprite from atlas var cachedAddressable = await AddressablePreloader.Load <SpriteAtlas>(atlasAddress); SpriteAtlas atlas = cachedAddressable.Result as SpriteAtlas; if (atlas != null) { Sprite spr = atlas.GetSprite(name); if (spr == null) { Debug.LogError($"Sprite [{name}] not found in atlas {atlasAddress}"); } return(spr); } else { Debug.LogError($"Atlas addressable [{name}] not found {atlasAddress}"); return(null); } /*var asyncOperationHandle = Addressables.LoadAssetAsync<SpriteAtlas>(atlasAddress); * await asyncOperationHandle.Task; * if (asyncOperationHandle.Result != null) * return asyncOperationHandle.Result.GetSprite(name); * else return null;*/ }
private async Task <T> LoadAsset() { //Just comment the try out if you want to just load by AssetAddress try { if (AssetReference.OperationHandle.Status == AsyncOperationStatus.None) { await AssetReference.LoadAssetAsync <T>().Task; StoredLoadedReference = AssetReference.Asset as T; return(StoredLoadedReference); } else { await AssetReference.LoadAssetAsync <T>().Task; StoredLoadedReference = AssetReference.Asset as T; return(StoredLoadedReference); } } catch { if (string.IsNullOrEmpty(AssetAddress)) { //Logger.LogError("Address is null for " + AssetReference.SubObjectName); return(null); } var validateAddress = Addressables.LoadResourceLocationsAsync(AssetAddress); await validateAddress.Task; if (validateAddress.Status == UnityEngine.ResourceManagement.AsyncOperations.AsyncOperationStatus.Succeeded) { if (validateAddress.Result.Count > 0) { // asset exists go ahead and load var AsynchronousHandle = Addressables.LoadAssetAsync <T>(AssetAddress); await AsynchronousHandle.Task; StoredLoadedReference = AsynchronousHandle.Result; return(StoredLoadedReference); } else { Logger.LogError("Address is invalid for " + AssetReference, Category.Addressables); } } } return(null); }
public static async Task <List <string> > DestinationLableAddress(IList <object> keys, Addressables.MergeMode mergeMode = Addressables.MergeMode.Intersection) { var handle = Addressables.LoadResourceLocationsAsync(keys, mergeMode); await handle.Task; IList <IResourceLocation> resourceLocations = handle.Result; List <string> addressList = new List <string>(); for (int i = 0; i < resourceLocations.Count; i++) { addressList.Add(resourceLocations[i].PrimaryKey); } return(addressList); }
private async Task LoadAndStoreAssets(string label) { var locations = await Addressables.LoadResourceLocationsAsync(label).Task; Debug.Log(Addressables.RuntimePath); List <GameObject> assets = new List <GameObject>(); foreach (var location in locations) { var prefab = await Addressables.LoadAssetAsync <GameObject>(location).Task; assets.Add(prefab); } _assetMap.Add(label, new List <GameObject>(assets)); }
IEnumerator example_GetAddress() { AssetReference MyRef1 = new AssetReference(); #region doc_AddressFromReference var opHandle = Addressables.LoadResourceLocationsAsync(MyRef1); yield return opHandle; if (opHandle.Status == AsyncOperationStatus.Succeeded && opHandle.Result != null && opHandle.Result.Count > 0) { Debug.Log("address is: " + opHandle.Result[0].PrimaryKey); } #endregion }
[System.Obsolete] //only because LoadResourceLocationsAsync now takes any IEnumerator rather than *just* a List IEnumerator example() { #region doc_LoadLocations AsyncOperationHandle <IList <IResourceLocation> > handle = Addressables.LoadResourceLocationsAsync( new string[] { "knight", "villager" }, Addressables.MergeMode.Union); yield return(handle); //... Addressables.Release(handle); #endregion }
/// <summary> /// Validates an addressable's address to ensure it points to an addressable asset /// </summary> /// <returns>True if the addressable has a valid address, False if it does not.</returns> public async Task <bool> HasValidAddress() { var validate = Addressables.LoadResourceLocationsAsync(AssetAddress); await validate.Task; if (validate.Status == AsyncOperationStatus.Succeeded) { if (validate.Result.Count > 0) { return(true); } } Logger.LogWarning($"Addressable Address is invalid: {AssetAddress}", Category.Addressables); return(false); }
/// <summary> /// Get the address of a given AssetReference. /// </summary> /// <param name="reference">The AssetReference you want to find the address of.</param> /// <returns>The address of a given AssetReference.</returns> public static string GetAddressFromAssetReference(AssetReference reference) { var loadResourceLocations = Addressables.LoadResourceLocationsAsync(reference); var result = loadResourceLocations.WaitForCompletion(); if (result.Count > 0) { string key = result[0].PrimaryKey; Addressables.Release(loadResourceLocations); return(key); } Addressables.Release(loadResourceLocations); return(string.Empty); }
private async Task GetAllLocations() { foreach (string label in _addressableLabels) { var unloadedLocations = await Addressables.LoadResourceLocationsAsync(label).Task; foreach (var location in unloadedLocations) { Debug.Log(string.Format("Adding {0} to locationdictionary", location)); if (!_cachedAddressableLocations.ContainsKey(location.PrimaryKey)) { _cachedAddressableLocations.Add(location.PrimaryKey, location); } } } }
public static IEnumerator LoadAssetLocationsAsync(string label, Action <List <IResourceLocation> > onLoadCompleted) { List <IResourceLocation> loadedLocations = new List <IResourceLocation>(); AsyncOperationHandle <IList <IResourceLocation> > locations = Addressables.LoadResourceLocationsAsync(label); yield return(locations); if (locations.Status == AsyncOperationStatus.Succeeded) { foreach (var l in locations.Result) { loadedLocations.Add(l); } } onLoadCompleted?.Invoke(loadedLocations); }
public IEnumerator TestAddressableAsyncLoad() { yield return(ValidateTestDependency()); PreInstall(); AsyncOperationHandle <GameObject> handle = default; Container.BindAsync <GameObject>().FromMethod(async() => { try { var locationsHandle = Addressables.LoadResourceLocationsAsync("TestAddressablePrefab"); await locationsHandle.Task; Assert.Greater(locationsHandle.Result.Count, 0, "Key required for test is not configured. Check Readme.txt in addressable test folder"); IResourceLocation location = locationsHandle.Result[0]; handle = Addressables.LoadAsset <GameObject>(location); await handle.Task; return(handle.Result); } catch (InvalidKeyException) { } return(null); }).AsCached(); PostInstall(); yield return(null); AsyncInject <GameObject> asycFoo = Container.Resolve <AsyncInject <GameObject> >(); int frameCounter = 0; while (!asycFoo.HasResult && !asycFoo.IsFaulted) { frameCounter++; if (frameCounter > 10000) { Addressables.Release(handle); Assert.Fail(); } yield return(null); } Addressables.Release(handle); Assert.Pass(); }
public static IEnumerator ValidateAndLoad <T>(string key, Action <T> callback) { var validateAddress = Addressables.LoadResourceLocationsAsync(key); yield return(validateAddress.Task); if (validateAddress.Status == UnityEngine.ResourceManagement.AsyncOperations.AsyncOperationStatus.Succeeded) { if (validateAddress.Result.Count > 0) { yield return(Load <T>(key, callback)); } } else { Debug.LogError("Error loading: " + key); } }
// Start is called before the first frame update void Start() { Debug.Log(Application.persistentDataPath); bool cachedFileLocation = File.Exists(Application.persistentDataPath); //audioSource = GetComponent<AudioSource>(); //image = GetComponent<Image>(); //Debug.Log(assetRefMember.SubObjectName); //Addressables.LoadResourceLocationsAsync(assetLabel.labelString).Completed += OnDownloadComplete; Addressables.LoadResourceLocationsAsync(spritenumber.labelString).Completed += LocationLoaded; Addressables.LoadResourceLocationsAsync(david.labelString).Completed += DavidLocationLoaded; }
public async Task SpawnThenRemoveAA(int amt, string label) { var location = await Addressables.LoadResourceLocationsAsync(label).Task; var objs = new List <GameObject>(); for (int i = 0; i < amt; i++) { objs.Add(await Addressables.InstantiateAsync(location[0]).Task); } await Task.Delay(TimeSpan.FromSeconds(5)); foreach (var obj in objs) { Addressables.Release(obj); } }
/// <summary> /// Get ResourceLocations for specified addressable label. If want to handle mutiple asset types in one call, /// use this API /// </summary> /// <param name="label"></param> /// <param name="rlHandler"></param> public async Task <IList <IResourceLocation> > LoadResourceLocationsForLabelAsync(string label) { //If already have resource location if (resourcesLocations.ContainsKey(label)) { //Just use it return(resourcesLocations[label]); } else { //Otherwise load the resource location var handle = Addressables.LoadResourceLocationsAsync(label); handles.Add(handle); await handle; resourcesLocations[label] = handle.Result; return(handle.Result); } }
// // Check key validity // public bool ValidateKeys(List <string> keys, CheckKeysCallback cb) { // Check whether keys are valid. if (running) { return(false); } running = true; checkKeysCallback = cb; keysSet = new HashSet <string>(keys); // Save for next function keyCheckHandle = Addressables.LoadResourceLocationsAsync(keys.ToArray(), Addressables.MergeMode.Union); keyCheckHandle.Completed += LocationsComplete; return(true); }
public static async Task InitAsync(Action <float>?onProgress, Action?onComplete) { var loadHandler = Addressables.LoadResourceLocationsAsync(SODatabaseSettings.Label); #pragma warning disable 4014 Task.Run(async() => { while (!loadHandler.IsDone) { CallAction(() => { onProgress?.Invoke(loadHandler.PercentComplete); }); await Task.Delay(50); } CallAction(() => { onProgress?.Invoke(loadHandler.PercentComplete); }); }); #pragma warning restore 4014 var resourceLocations = await loadHandler.Task; var loadTasks = resourceLocations.ToDictionary(resourceLocation => resourceLocation.PrimaryKey.Substring(SODatabaseSettings.Path.Length), resourceLocation => Addressables.LoadAssetAsync <DataNode>(resourceLocation).Task); await Task.WhenAll(loadTasks.Values); root = new FolderHolder(); foreach (var loadTask in loadTasks) { //SODatabase/Example1Folder/Example1.asset var pathElements = loadTask.Key.Split('/'); var curFolder = root; for (var i = 0; i < pathElements.Length - 1; i++) { if (!curFolder.FolderHolders.ContainsKey(pathElements[i])) { curFolder.FolderHolders.Add(pathElements[i], new FolderHolder()); } curFolder = curFolder.FolderHolders[pathElements[i]]; } var dataNodeName = pathElements[pathElements.Length - 1]; dataNodeName = dataNodeName.Substring(0, dataNodeName.IndexOf(".asset", StringComparison.Ordinal)); curFolder.DataNodes.Add(dataNodeName, loadTask.Value.Result); } CallAction(onComplete); }
private async Task SortWaitToComplete(List <string> labels) { // NOTE: Sort the addressables based on the first label. // var locations = await Addressables.LoadResourceLocationsAsync( // labels.ToArray(), Addressables.MergeMode.UseFirst).Task; // NOTE: Sort the addressables based on all the labels. // var locations = await Addressables.LoadResourceLocationsAsync( // labels.ToArray(), Addressables.MergeMode.Union).Task; // NOTE: Sort the addressables which contain all the labels. var locations = await Addressables.LoadResourceLocationsAsync( labels.ToArray(), Addressables.MergeMode.Intersection).Task; foreach (var location in locations) { Addressables.InstantiateAsync(location); } }
/// <summary> /// Load a single addressable resource /// </summary> /// <typeparam name="T"></typeparam> /// <param name="name"></param> /// <param name="label"></param> /// <param name="resourceLoadedCallback"></param> public async Task <T> LoadResourceAsync <T>(string name, string label) { //LoadResources<T>(new List<string> { key }, label, (key, resource) => resourceLoadedCallback(resource)); if (label == null) { return(await LoadResourceAsync <T>(name)); } else if (name == null) { Assert.IsNotNull(name, "Name shouldn't be null"); return(default(T)); } else { string storeKey = name + "_" + label + typeof(T).ToString(); //If we already loaded the resource if (resources.ContainsKey(storeKey)) { //Use it directly return((T)resources[storeKey]); } else { var handle = Addressables.LoadResourceLocationsAsync(new List <object> { name, label }, Addressables.MergeMode.Intersection); handles.Add(handle); await handle; var resourceSelector = handle.Result.Select(rl => LoadResourceByLocationAsync <T>(rl)); await Task.WhenAll(resourceSelector); foreach (var result in resourceSelector) { var resource = await result; resources[storeKey] = resource; return(resource); } return(default(T)); } } }
public override void LoadAllFileListAsync(Action <LocalizationFile[]> complete) { if (complete != null) { Addressables.LoadResourceLocationsAsync(KLocalizeFolder).Completed += handle => { List <LocalizationFile> fileList = new List <LocalizationFile>(); if (handle.Status == AsyncOperationStatus.Succeeded) { foreach (var file in handle.Result) { LocalizationFile data = new LocalizationFile(file.PrimaryKey); fileList.Add(data); } } complete(fileList.ToArray()); }; } }
public static IEnumerator UpdateLocalProtos(bool forceUpdate = false) { if (!Directory.Exists(ProtoConst.protoResDir)) { Directory.CreateDirectory(ProtoConst.protoResDir); } var resHandle = Addressables.LoadResourceLocationsAsync(ProtoConst.label, typeof(TextAsset)); yield return(resHandle); for (int i = 0; i < resHandle.Result.Count; i++) { string key = resHandle.Result[i].PrimaryKey; if (!key.StartsWith(ProtoConst.address)) { continue; } string path = string.Format("{0}/{1}", ProtoConst.protoResDir, key.Substring(5, key.Length - 11)); if (!forceUpdate && File.Exists(path)) { var downloadSizeHandle = Addressables.GetDownloadSizeAsync(key); yield return(downloadSizeHandle); if (downloadSizeHandle.Result == 0) { Addressables.Release(downloadSizeHandle); continue; } } var loadHandle = Addressables.LoadAssetAsync <TextAsset>(key); yield return(loadHandle); string dir = Path.GetDirectoryName(path); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } File.WriteAllBytes(path, loadHandle.Result.bytes); Addressables.Release(loadHandle); } Addressables.Release(resHandle); }
private IEnumerator FindSceneLocationRoutine(string sceneName, Action onSuccess, Action <string> onFail) { var resourceLocationHandle = Addressables.LoadResourceLocationsAsync(sceneName); while (resourceLocationHandle.IsValid() && !resourceLocationHandle.IsDone) { Debug.Log("Awaiting scene location... " + resourceLocationHandle.PercentComplete * 100f); yield return(new WaitForSecondsRealtime(0.1f)); } if (resourceLocationHandle.Status != AsyncOperationStatus.Succeeded || resourceLocationHandle.Result.Count == 0) { Debug.Log("Scene location for " + sceneName + " has not been found!"); StopFindSceneLocation(); onFail.Invoke("Scene location for " + sceneName + " has not been found!"); yield break; } Debug.Log("Scene location found! " + resourceLocationHandle.Result[0]); StopFindSceneLocation(); onSuccess.Invoke(); }
public IEnumerator GetSpriteAsync(string key, Action <Sprite> callback) { if (!spriteDic.ContainsKey(key)) { switch (sourceType) { case SourceType.Resources: var progress = Resources.LoadAsync <Sprite>(Path.Combine(imagePath, key).Replace("\\", "/")); yield return(new WaitUntil(() => progress.isDone)); spriteDic.Add(key, progress.asset as Sprite); break; #if ADDRESSABLE_EXISTS case SourceType.Addressable: var finalPath = useFormatPath ? string.Format(imagePath, key) : Path.Combine(imagePath, key).Replace("\\", "/"); var pathProgress = Addressables.LoadResourceLocationsAsync(finalPath); yield return(pathProgress); if (pathProgress.Result.Count > 0) { var progress3 = Addressables.LoadAssetAsync <Sprite>(finalPath); yield return(progress3); spriteDic.Add(key, progress3.Result); } break; #endif case SourceType.Custom: yield return(provider.GetSprite(key, result => { spriteDic.Add(key, result); })); break; } } callback(spriteDic.ContainsKey(key) ? spriteDic[key] : null); yield break; }
public async ETTask Load() { // 预先加载的资源 var resourceLocations = Addressables.LoadResourceLocationsAsync("preload"); IList <IResourceLocation> locations = await resourceLocations.Task; // 预先下载的资源大小 long downloadSize = await Addressables.GetDownloadSizeAsync("preload").Task; Log.Info($"预先下载资源大小:{downloadSize}"); this.DownloadHandle = Addressables.DownloadDependenciesAsync(locations, false); this.TimerId = Game.Scene.GetComponent <TimerComponent>() .NewRepeatedTimer(1000, b => { var e = new ResUpdateEvent { Percent = this.DownloadHandle.GetDownloadStatus().Percent, Status = this.DownloadHandle.Status, }; EventBus.Publish(e); }); await this.DownloadHandle.Task; TimerComponent.Instance.Remove(this.TimerId); // 加载完成事件 EventBus.Publish(new ResUpdateEvent { Percent = this.DownloadHandle.GetDownloadStatus().Percent, Status = this.DownloadHandle.Status }); // 资源下载完成,开始加载预加载资源。 if (this.DownloadHandle.Status == AsyncOperationStatus.Succeeded) { await Preload(); } // 清理 Addressables.Release(this.DownloadHandle); }
public static void LoadSpritesLabel(string label, Action <Dictionary <Enemies, List <Sprite> > > callback) { LoadCount++; Dictionary <Enemies, List <Sprite> > items = new Dictionary <Enemies, List <Sprite> >(); AsyncOperationHandle <IList <IResourceLocation> > labelOperation = Addressables.LoadResourceLocationsAsync(label); labelOperation.Completed += (labelResponse) => { int totalCount = labelResponse.Result.Count; foreach (IResourceLocation item in labelResponse.Result) { AsyncOperationHandle <Sprite[]> resourceOperation = Addressables.LoadAssetAsync <Sprite[]>(item.PrimaryKey); resourceOperation.Completed += (result) => { totalCount--; switch (labelResponse.Status) { case AsyncOperationStatus.Succeeded: Enum.TryParse(Path.GetFileNameWithoutExtension(item.PrimaryKey), out Enemies enemyType); items.Add(enemyType, result.Result.ToList()); Addressables.Release(resourceOperation); break; case AsyncOperationStatus.Failed: Debug.LogError("Failed to load audio clips."); break; default: break; } // When we've finished loading all items in the directory, let's continue if (totalCount == 0) { LoadCount--; callback(items); ShouldLaunch(); } }; } }; }