public static void InstantiateAsync(string name, UnityAction <GameObject> Completed, int MaxPoolCount = 0) { if (!Instance.AllPools.ContainsKey(name)) { Instance.AllPools.Add(name, new PoolItem(name, MaxPoolCount)); //$"创建了个新的池子<{name}>".Log(); } if (Instance.AllPools[name].Pools.Count > 0) { Instance.AllPools[name].Pools[0].ResetTrans(); Instance.AllPools[name].Pools[0].ReShow(); Completed?.Invoke(Instance.AllPools[name].Pools[0]); Instance.AllPools[name].Pools.RemoveAt(0); } else { Addressables.InstantiateAsync($"{name}.prefab").Completed += x => { x.Result.transform.SetParent(Instance.transform); Completed?.Invoke(x.Result); //移除的时候根据name分配池子 x.Result.name = name; }; } }
private void Start() { var offset = new Vector3((Map.Column - 1) / 2.0f, 0, (Map.Row - 1) / 2.0f); for (int c = 0; c < Map.Column; c++) { for (int r = 0; r < Map.Row; r++) { var h = Addressables.InstantiateAsync("Floor"); var floor = h.WaitForCompletion(); var f = floor.EnsureComponent <Floor>(); f.name = $"{r}_{c}"; f.Pos = new int2(c, r); f.transform.position = new Vector3(f.Pos.x, 0, f.Pos.y) - offset; var rand = Random.Range(0, 100); if (rand > 60) { f.SetFloor(FloorType.Block); } else { f.SetFloor(FloorType.None); } Map.AddFloorCache(f); } } }
private async UniTaskVoid Initialize() { Controller.I.AddRpcContainer(this); // Controller.I.OnAppPause += DestroyLobby; await UniTask.DelayFrame(1); var containerRoot = new GameObject("Lobby").transform; new LobbyReferences(); LobbyReferences.I.Canvas = (await Addressables.InstantiateAsync("canvas", containerRoot)) .GetComponent <Transform>(); await FriendsView.Create(); SoundButton.Create(); await PersonalActiveUserView.Create(); await RoomRequester.Create(); await Shop.Create(LobbyReferences.I.Canvas, ItemType.Cardback); await Shop.Create(LobbyReferences.I.Canvas, ItemType.Background); #if HMS IapShop.Create(); #endif Background.I.SetForLobby(); }
public void CreateCubeOnButton() { Addressables.InstantiateAsync("Cube", Vector3.zero, Quaternion.identity).Completed += handle => { MyCube = handle.Result; }; }
public void CreatFightUi() { Addressables.InstantiateAsync("FightUi", transform.parent); Addressables.InstantiateAsync("HomeUi", transform.parent); Clean(); Destroy(gameObject); }
/// <summary> /// because of the parent, it's destroyed with module group /// </summary> public static async UniTask Create() { I = (await Addressables.InstantiateAsync("background")).GetComponent <Background>(); I.GetComponent <Canvas>().worldCamera = Camera.main; I.transform.SetSiblingIndex(0); }
private async UniTask <TComponentType> CreateInstanceAsync <TComponentType>(string componentId, Transform parent = null) where TComponentType : Component { var handle = Addressables.InstantiateAsync(componentId, parent, false); return(await HandleAddressableCreation <TComponentType>(handle)); }
public IEnumerator DoLoading() { int w = Config.CardArtWidth; int h = Config.CardArtHeight; // I'm doing it sequentually to be considerate to the website and not DoS it - @micktu for (int i = 0; i < CardImages.Length; i++) { float salt = UnityEngine.Random.value; // Prevent Unity from caching - @micktu UnityWebRequest request = UnityWebRequest.Get($"https://picsum.photos/{w}/{h}?p={salt}"); yield return(request.SendWebRequest()); Texture2D image = new Texture2D(w, h); image.LoadImage(request.downloadHandler.data); CardImages[i] = image; } // Addressables flex var handle = Addressables.InstantiateAsync("CardManager"); yield return(handle); CardManager = handle.Result.GetComponent <CardManager>(); CardManager.Init(this); EnterState(GameState.Playing); }
public static AsyncOperationHandle <GameObject> InstantiateAsync(string pAddress, Action <float> pProgress = null, Action <GameObject> pOnCompleted = null) { var operation = Addressables.InstantiateAsync(pAddress); WaitLoadTask(operation, pProgress, pOnCompleted); return(operation); }
public async Task Init(Transform parent) { string poolName = string.Empty; AsyncOperationHandle <GameObject> op = Addressables.LoadAssetAsync <GameObject>(Object); op.Completed += (o) => { poolName = o.Result.name; }; await op.Task; GameObject poolRoot = new GameObject(poolName + "Pool"); poolRoot.transform.SetParent(parent); _root = poolRoot.transform; for (int i = 0; i < StartAmount; i++) { AsyncOperationHandle <GameObject> handler = Addressables.InstantiateAsync(Object, poolRoot.transform); handler.Completed += (obj => { obj.Result.SetActive(false); _objects.Push(obj.Result); }); await handler.Task; } }
public override IEnumerator Spawn(TrackSegment segment, float t) { Vector3 position; Quaternion rotation; segment.GetPointAt(t, out position, out rotation); AsyncOperationHandle op = Addressables.InstantiateAsync(gameObject.name, position, rotation); yield return(op); if (op.Result == null || !(op.Result is GameObject)) { Debug.LogWarning(string.Format("Unable to load obstacle {0}.", gameObject.name)); yield break; } GameObject obj = op.Result as GameObject; obj.transform.SetParent(segment.objectRoot, true); //TODO : remove that hack related to #issue7 Vector3 oldPos = obj.transform.position; obj.transform.position += Vector3.back; obj.transform.position = oldPos; }
IEnumerator ShotLoop() { while (true) { if (Shot && !IsShooting && lockOn.LockedEnemys.Count > 0) { int BulletCount = lockOn.LockedEnemys.Count; Debug.Log("Shot [x" + BulletCount.ToString() + "]"); Addressables.InstantiateAsync(BulletSound).Completed += op => { op.Result.GetComponent <BulletSound>().Initialize(BulletCount); }; IsShooting = true; for (int i = 0; i < BulletCount; i++) { IndexDirection = new Vector3(Random.value, Random.value, Random.value); Addressables.InstantiateAsync(BulletAsset).Completed += op => { if (lockOn.LockedEnemys.Count > 0) { op.Result.GetComponent <Bullet>()?.Initialize(transform.position, IndexDirection, lockOn.LockedEnemys[0]); lockOn.LockedEnemys.RemoveAt(0); } }; if (i == lockOn.LockOnLimit - 1) { Quantize.QuantizePlay(MaxShot); } yield return(new WaitForSeconds(ShotInterval)); } IsShooting = false; } yield return(new WaitForSeconds(ShotInterval)); } }
static async public void InstantiateAsync(string key, System.Action <GameObject, object> onComplete, System.Action <object, object> onEnd, object userData = null, Transform parent = null) { if (m_MarkGroup) { m_Groupes.Add(key); m_TotalGroupCount++; } var task = Addressables.InstantiateAsync(key, parent, false).Task; await task; if (task.Result != null) { if (onComplete != null) { onComplete(task.Result, userData); } } else { if (onEnd != null) { onEnd(key, userData); } } OnItemLoaded(key); }
/// <summary> /// Load & Instantiate Asset. this will be helpful if we deal with prefabs (ex: slots) /// </summary> /// <param name="assetReference"> target asset reference </param> public void Instantiate <T>(AssetReference assetReference, Action <T> onComplete, Action <string> onFailed = null) where T : MonoBehaviour, IAsset { if (assetReference == null) { throw new NullReferenceException($"AssetReference must be not null!"); } var operation = Addressables.InstantiateAsync(assetReference); operation.Completed += (response) => { switch (operation.Status) { case AsyncOperationStatus.Failed: onFailed?.Invoke(operation.PercentComplete.ToString()); break; case AsyncOperationStatus.Succeeded: var asset = response.Result.GetComponent <IAsset>(); asset.OnDestroyed += () => { Addressables.ReleaseInstance(response.Result); }; //release onComplete?.Invoke(response.Result.GetComponent <T>()); break; default: Debug.LogError("No Result > " + response.Result); break; } }; }
private async Task <PoolObject> InstantiateAsync(object key) { IResourceLocation location = AddressablesPoolUtility.GetResourceLocation <GameObject>(key); PoolObject poolObject; //If location is initially null, means the internal ResourceManager has not alloced, so instantiate //by string key to trigger that. if (location == null) { AsyncOperationHandle <GameObject> handle = Addressables.InstantiateAsync(key, trackHandle: false); await handle.Task; location = AddressablesPoolUtility.GetResourceLocation <GameObject>(key); poolObject = AddNewUsedObject(handle.Result, handle, location); return(poolObject); } poolObject = RetrieveObject(location.PrimaryKey); if (poolObject == null) { AsyncOperationHandle <GameObject> handle = Addressables.InstantiateAsync(location, trackHandle: false); await handle.Task; poolObject = AddNewUsedObject(handle.Result, handle, location); return(poolObject); } else { _usedObjects.Add(poolObject.Handle.Result, poolObject); return(poolObject); } }
public void InstantiateObjects(int amount = 1) { foreach (var operationHandle in _operationHandles) { Addressables.InstantiateAsync(operationHandle.Key); } }
public static async UniTask Show(string message = null, Action dismissButtonAction = null) { if (i) { Destroy(i.gameObject); } //you can remove this to support multiple panels //but the new should draw over the old i = (await Addressables.InstantiateAsync("blockingPanel", ProjectReferences.I.Canvas)) .GetComponent <BlockingPanel>(); if (dismissButtonAction != null) { i.dismissButton.onClick.AddListener(() => dismissButtonAction()); //if you want to reuse the same object make sure to save and remove this i.dismissButton.gameObject.SetActive(true); } else { i.dismissButton.gameObject.SetActive(false); } i.messageText.text = message ?? ""; animTween = i.waitImage.transform.DORotate(Vector3.forward * 180, 2f) .SetLoops(9999, LoopType.Yoyo); }
public void SpawnJwellPieces() { container.SetActive(true); var totalJeweleryPiece = _levelManager.GetCurrentLevel().jewelleryPieces.Length; for (int i = 0; i < totalJeweleryPiece; i++) { var quantity = _levelManager.GetCurrentLevel().jewelleryPieces[i].quantity; //Debug.Log(quantity); for (int j = 0; j <= quantity; j++) { Addressables.InstantiateAsync(_levelManager.GetCurrentLevel().jewelleryPieces[i].Prefab, jwellerySpawnPoint).Completed += g => { if (g.Status == AsyncOperationStatus.Succeeded) { //var result = g.Result; g.Result.transform.position = new Vector3(jwellerySpawnPoint.position.x + Random.Range(-_offset, _offset), jwellerySpawnPoint.position.y, jwellerySpawnPoint.position.z + Random.Range(-_offset, _offset)); assetsInMemory.Add(g.Result); } }; } } }
public static async void LoadAndInstantiate(string name, Vector3 position, Quaternion rotation, Transform parent = null, Action <GameObject> onLoad = null) { GameObject obj = await Addressables.InstantiateAsync(name, position, rotation, parent).Task; onLoad?.Invoke(obj); Debug.Log($"[ResourcesManager]生成了{name}"); }
public AsyncResult InstantiateAsync <T>(IList <string> key, Action <T> callBack = null) where T : class { var result = new AsyncResult(); Action <GameObject> fun = (GameObject obj) => { result.IsDone = true; result.Result = obj; callBack?.Invoke(obj as T); }; if (checkPool.ContainsKey(key[0])) { InstantiateIRes(checkPool[key[0]], fun); } else { LoadAssetAsync(key[0], (obj) => { if (obj == null) { return; } var h = Addressables.InstantiateAsync(key[0]); h.Completed += (hand) => { fun(hand.Result); }; }); } return(result); }
IEnumerator SpawnWaves() { yield return(new WaitForSeconds(startWait)); while (true) { for (int i = 0; i < hazardCount; i++) { var hazardAddress = hazardLocations[Random.Range(0, hazardLocations.Count)]; Vector3 spawnPosition = new Vector3(Random.Range(-spawnValues.x, spawnValues.x), spawnValues.y, spawnValues.z); Quaternion spawnRotation = Quaternion.identity; // ADDRESSABLES UPDATES Addressables.InstantiateAsync(hazardAddress, spawnPosition, spawnRotation); yield return(new WaitForSeconds(spawnWait)); } yield return(new WaitForSeconds(waveWait)); if (gameOver) { restartText.text = "Press 'R' for Restart"; restart = true; break; } } }
public async virtual void Show(string uiName, Action complete = null) { if (!_views.ContainsKey(uiName)) { var go = await Addressables.InstantiateAsync(uiName, _root).Task; _views[uiName] = GetNewView(uiName, go); SetLayerParent(_views[uiName], _layerMgr); } IView view = _views[uiName]; var layer = view.Self.GetComponent <ILayer>(); if (layer.Layer == UILayer.BASE_UI) { //正在显示的base界面隐藏 if (_baseUiStack.Count > 0) { _baseUiStack.Peek().Hide(); } //显示当前要显示的界面 UIStack group = new UIStack(uiName, view); _baseUiStack.Push(group); } else { _baseUiStack.Peek().Show(uiName, view); } if (complete != null) { complete(); } }
// Start is called before the first frame update void Start() { Addressables.InstantiateAsync("Cube1"); GameObject obj = Resources.Load <GameObject>("Cube"); Instantiate(obj); }
public static async UniTaskVoid Create(FullUserInfo fullUserInfo, UserRoomStatus oppoRoomResult, Transform parent) { var asset = await Addressables.InstantiateAsync("finalMuv", parent); asset.GetComponent <FinalMuv>().Init(fullUserInfo, oppoRoomResult); }
public IEnumerator GetObjectAsync(string key, Action <GameObject> callback) { switch (sourceType) { case SourceType.Resources: var progress = Resources.LoadAsync <GameObject>(Path.Combine(objectPath, key).Replace("\\", "/")); yield return(new WaitUntil(() => progress.isDone)); callback(GameObject.Instantiate(progress.asset as GameObject)); break; #if ADDRESSABLE_EXISTS case SourceType.Addressable: var finalPath = useFormatPath ? string.Format(objectPath, key) : Path.Combine(objectPath, key).Replace("\\", "/"); var progress3 = Addressables.InstantiateAsync(finalPath); yield return(new WaitUntil(() => progress3.IsDone)); callback(progress3.Result); break; #endif case SourceType.Custom: yield return(provider.GetObject(key, result => { callback(result); })); break; } }
public void OnShapeDetected(ShapeDetector.ShapeInfo info) { // Debug.Log(info.type.ToString() + " : " + info.position.ToString("F3")); if (info.type == ShapeDetector.ShapeType.Circle) { Addressables.InstantiateAsync(MagicCircle).Completed += op => { op.Result.GetComponent <MagicCircle>()?.Initialize(info.position, info.rotation); } } ; } IEnumerator DestroyLine(LineRenderer line, float waitTime) { float t = Time.time; while (Time.time < t + waitTime) { Color s = line.startColor, e = line.endColor; s.a = e.a = 1 - ((Time.time - t) / waitTime) > 0 ? 1 - ((Time.time - t) / waitTime) : 0; line.startColor = s; line.endColor = e; yield return(null); } line.startColor = line.endColor = new Color(0, 0, 0, 0); UnityEngine.AddressableAssets.Addressables.ReleaseInstance(this.gameObject); } }
IEnumerator ShowEffect() { { var ao = Addressables.InstantiateAsync("prefabs/cube.prefab"); ao.Completed += handle => { GameObject obj = ao.Result; obj.transform.position = Vector3.zero; obj.transform.localScale = Vector3.one; }; yield return(ao); } Addressables.ReleaseInstance(gameObject); // Addressables.ClearResourceLocators(); Addressables.ClearDependencyCacheAsync("prefabs/launch.prefab"); { var rootLayer = GameObject.Find("LaunchLayer").GetComponent <Canvas>(); var loader = KVResourceMgr.Instance.LoadAssetAsync("prefabs/launch.prefab"); yield return(loader); // ao.Completed += handle => // { GameObject obj = loader.asset as GameObject; obj = Instantiate(obj, rootLayer.transform); obj.transform.localPosition = Vector3.zero; obj.transform.localScale = Vector3.one; // }; // yield return ao; } DestroyImmediate(gameObject); }
IEnumerator ShotLoop() { while (true) { if (IsShooting && lockOn.LockedEnemys.Count > 0) { int BulletCount = lockOn.LockedEnemys.Count; Debug.Log("Barrier [x" + BulletCount.ToString() + "]"); for (int i = 0; i < BulletCount; i++) { float pitch = 1f + 0.1f * i; Addressables.InstantiateAsync(BarrierBox).Completed += op => { if (lockOn.LockedEnemys.Count > 0) { op.Result.GetComponent <BarrierBox>()?.Initialize(lockOn.LockedEnemys[0], pitch); lockOn.LockedEnemys.RemoveAt(0); } }; yield return(new WaitForSeconds(ShotInterval)); } } yield return(new WaitForSeconds(ShotInterval)); } }
public IEnumerator CreateView(IUIPanel uiPanel) { string assetPath = uiPanel.GetPanelAssetPath(); Logger.d($"[DeftauleUISystem.Create] UI预制体加载 assetPath={assetPath}"); var loader = Addressables.InstantiateAsync(assetPath, _uiPanelRoot, false); yield return(loader); if (loader.Status == AsyncOperationStatus.Succeeded) { UIPanelData panelData = new UIPanelData(); _uiPanelDatas.Add(panelData); panelData.PanelGO = loader.Result; panelData.UIPanel = uiPanel; panelData.PanelGO.GetComponent <Canvas>().enabled = false; panelData.PanelGO.GetComponent <GraphicRaycaster>().enabled = false; uiPanel.OnInit(loader.Result); } else { Logger.e($"[DeftauleUISystem.Create] UI预制体加载失败 assetPath={assetPath}"); } }
public static GameObject Instantiate(object key, Transform parent = null, bool instantiateInWorldSpace = false) { if (!s_Initialized) { throw new Exception("Whoa there friend! We haven't init'd yet!"); } var op = Addressables.InstantiateAsync(key, parent, instantiateInWorldSpace); if (!op.IsDone) { throw new Exception("Sync Instantiate failed to finish! " + key); } if (op.Result == null) { var message = "Sync Instantiate has null result " + key; if (op.OperationException != null) { message += " Exception: " + op.OperationException; } throw new Exception(message); } return(op.Result); }