private void OnLoadComplete(object sender, AssetsProxy assetsproxy, object data) { AssetsLoader loader = ( AssetsLoader )sender; ArrayList al = ( ArrayList )loader.data; LoadCompleteCallback onSuccess = ( LoadCompleteCallback )al[0]; Texture2D texture = assetsproxy.LoadAsset <Texture2D>(loader.assetName); onSuccess?.Invoke(texture); }
/// <summary> /// Load an asset asynchronously into memory. /// </summary> public void Load <TObject>(string key, LoadCompleteCallback <TObject> onComplete = null) where TObject : UnityEngine.Object { if (IsLoaded(typeof(TObject), key)) { onComplete?.Invoke(true, Get <TObject>(key)); return; } _numLoadCalls++; // when multiple identical load calls all happen at the same time, we don't want to execute them all, // we just need to load once and distribute the result to all the callbacks if (IsLoading(typeof(TObject), key)) { if (!_typeToKeyToDuplicateLoadCallbacks.TryGetValue(typeof(TObject), out Dictionary <string, List <Action> > keyToDuplicateLoadCallbacks)) { keyToDuplicateLoadCallbacks = new Dictionary <string, List <Action> >(); _typeToKeyToDuplicateLoadCallbacks.Add(typeof(TObject), keyToDuplicateLoadCallbacks); } if (!keyToDuplicateLoadCallbacks.TryGetValue(key, out List <Action> duplicateLoadCallbacks)) { duplicateLoadCallbacks = new List <Action>(); keyToDuplicateLoadCallbacks.Add(key, duplicateLoadCallbacks); } duplicateLoadCallbacks.Add(() => { // by the time this executes, the asset should be loaded TObject payload = Get <TObject>(key); _numCompletions++; onComplete?.Invoke(payload != null, payload); }); // return, we'll execute the callback when the first load call completes return; } // record that we are already loading this asset if (!_loadingAssets.TryGetValue(typeof(TObject), out HashSet <string> loadingKeys)) { loadingKeys = new HashSet <string>(); _loadingAssets.Add(typeof(TObject), loadingKeys); } loadingKeys.Add(key); Addressables.LoadAssetAsync <TObject>(key).Completed += (AsyncOperationHandle <TObject> obj) => { _numCompletions++; if (obj.Result == null) { Debug.LogErrorFormat("the asset loaded with the key {0} is null", key); } else { if (!_loadedAssets.ContainsKey(typeof(TObject))) { _loadedAssets.Add(typeof(TObject), new Dictionary <string, UnityEngine.Object>()); } _loadedAssets[typeof(TObject)].Add(key, obj.Result as TObject); loadingKeys.Remove(key); } onComplete?.Invoke(obj.Result != null, obj.Result as TObject); // now invoke any of the duplicate load complete callbacks if (_typeToKeyToDuplicateLoadCallbacks.ContainsKey(typeof(TObject))) { if (_typeToKeyToDuplicateLoadCallbacks[typeof(TObject)].ContainsKey(key)) { foreach (Action callback in _typeToKeyToDuplicateLoadCallbacks[typeof(TObject)][key]) { callback?.Invoke(); } _typeToKeyToDuplicateLoadCallbacks[typeof(TObject)][key].Clear(); } } }; }