Example #1
0
        /// <inheritdoc/>
        public AsyncOperationHandle <SceneInstance> ReleaseScene(ResourceManager resourceManager, AsyncOperationHandle <SceneInstance> sceneLoadHandle)
        {
            var unloadOp = new UnloadSceneOp();

            unloadOp.Init(sceneLoadHandle);
            return(resourceManager.StartOperation(unloadOp, sceneLoadHandle));
        }
 public static UniTask <T> ToUniTask <T>(this AsyncOperationHandle <T> asyncOperation)
 {
     Error.ThrowArgumentDefaultException(asyncOperation, nameof(asyncOperation));
     return(new UniTask <T>(new AsyncOperationHandleAwaiter <T>(asyncOperation)));
 }
Example #3
0
 void FinishByInstantiate(AsyncOperationHandle <GameObject> go)
 {
     GameObject.Instantiate(go.Result);
 }
 private void OnAssetInstantiated(AsyncOperationHandle <GameObject> asyncOp)
 {
     Debug.Log(asyncOp.Result.name + " loaded.");
 }
 public static async UniTask <SceneInstance> UnloadSceneAsync(AsyncOperationHandle <SceneInstance> handle, bool autoReleaseHandle = true, IProgress <float> progress = null, PlayerLoopTiming playerLoopTiming = PlayerLoopTiming.Update, CancellationToken cancellationToken = default)
 {
     return(await Addressables.UnloadSceneAsync(handle, autoReleaseHandle).ConfigureAwait(progress, playerLoopTiming, cancellationToken));
 }
Example #6
0
 private void LoadEventChannel(AsyncOperationHandle <SceneInstance> obj)
 {
     // Waiting for LoadSceneRequest asset to load
     _loadSceneRequest.LoadAssetAsync <LoadSceneRequestSO>().Completed += LoadMainScreen;
 }
    public IEnumerator SpawnCoinAndPowerup(TrackSegment segment)
    {
        if (!m_IsTutorial)
        {
            const float increment       = 1.5f;
            float       currentWorldPos = 0.0f;
            int         currentLane     = Random.Range(0, 3);

            float powerupChance = Mathf.Clamp01(Mathf.Floor(m_TimeSincePowerup) * 0.5f * 0.01f);
            float premiumChance = Mathf.Clamp01(Mathf.Floor(m_TimeSinceLastPremium) * 0.5f * 0.001f);

            while (currentWorldPos < segment.worldLength)
            {
                Vector3    pos;
                Quaternion rot;
                segment.GetPointAtInWorldUnit(currentWorldPos, out pos, out rot);


                bool laneValid  = true;
                int  testedLane = currentLane;
                while (Physics.CheckSphere(pos + ((testedLane - 1) * laneOffset * (rot * Vector3.right)), 0.4f, 1 << 9))
                {
                    testedLane = (testedLane + 1) % 3;
                    if (currentLane == testedLane)
                    {
                        // Couldn't find a valid lane.
                        laneValid = false;
                        break;
                    }
                }

                currentLane = testedLane;

                if (laneValid)
                {
                    pos = pos + ((currentLane - 1) * laneOffset * (rot * Vector3.right));


                    GameObject toUse = null;
                    if (Random.value < powerupChance)
                    {
                        int picked = Random.Range(0, consumableDatabase.consumbales.Length);

                        //if the powerup can't be spawned, we don't reset the time since powerup to continue to have a high chance of picking one next track segment
                        if (consumableDatabase.consumbales[picked].canBeSpawned)
                        {
                            // Spawn a powerup instead.
                            m_TimeSincePowerup = 0.0f;
                            powerupChance      = 0.0f;

                            AsyncOperationHandle op = Addressables.InstantiateAsync(consumableDatabase.consumbales[picked].gameObject.name, pos, rot);
                            yield return(op);

                            if (op.Result == null || !(op.Result is GameObject))
                            {
                                Debug.LogWarning(string.Format("Unable to load consumable {0}.", consumableDatabase.consumbales[picked].gameObject.name));
                                yield break;
                            }
                            toUse = op.Result as GameObject;
                            toUse.transform.SetParent(segment.transform, true);
                        }
                    }
                    else if (Random.value < premiumChance)
                    {
                        m_TimeSinceLastPremium = 0.0f;
                        premiumChance          = 0.0f;

                        AsyncOperationHandle op = Addressables.InstantiateAsync(currentTheme.premiumCollectible.name, pos, rot);
                        yield return(op);

                        if (op.Result == null || !(op.Result is GameObject))
                        {
                            Debug.LogWarning(string.Format("Unable to load collectable {0}.", currentTheme.premiumCollectible.name));
                            yield break;
                        }
                        toUse = op.Result as GameObject;
                        toUse.transform.SetParent(segment.transform, true);
                    }
                    else
                    {
                        toUse = Coin.coinPool.Get(pos, rot);
                        toUse.transform.SetParent(segment.collectibleTransform, true);
                    }

                    if (toUse != null)
                    {
                        //TODO : remove that hack related to #issue7
                        Vector3 oldPos = toUse.transform.position;
                        toUse.transform.position += Vector3.back;
                        toUse.transform.position  = oldPos;
                    }
                }

                currentWorldPos += increment;
            }
        }
    }
Example #8
0
        /// <summary>
        /// Load the <typeparamref name="TObject"/> at the specified <paramref name="location"/>.
        /// </summary>
        /// <returns>An async operation.</returns>
        /// <param name="location">Location to load.</param>
        /// <typeparam name="TObject">Object type to load.</typeparam>
        public AsyncOperationHandle <TObject> ProvideResource <TObject>(IResourceLocation location)
        {
            AsyncOperationHandle handle = ProvideResource(location, typeof(TObject));

            return(handle.Convert <TObject>());
        }
Example #9
0
 /// <summary>
 /// Registers an operation with the ResourceManager. The operation will be executed when the <paramref name="dependency"/> completes.
 /// This should only be used when creating custom operations.
 /// </summary>
 /// <returns>The AsyncOperationHandle used to access the result and status of the operation.</returns>
 /// <param name="operation">The custom AsyncOperationBase object</param>
 /// <param name="dependency">Execution of the operation will not occur until this handle completes. A default handle can be passed if no dependency is required.</param>
 /// <typeparam name="TObject">Object type associated with this operation.</typeparam>
 public AsyncOperationHandle <TObject> StartOperation <TObject>(AsyncOperationBase <TObject> operation, AsyncOperationHandle dependency)
 {
     operation.Start(this, dependency, m_UpdateCallbacks);
     return(operation.Handle);
 }
 private void Op_Completed(AsyncOperationHandle <GameObject> obj)
 {
     throw new NotImplementedException();
 }
        /*
         * public override IEnumerator GetGameObjectAsync(IOut<GameObject> gameObject)
         * {
         *  AsyncOperationHandle<GameObject> seatruckFabricatorModuleRequest = AddressablesUtility.LoadAsync<GameObject>("WorldEntities/Tools/SeaTruckFabricatorModule.prefab");
         *  yield return seatruckFabricatorModuleRequest;
         *  GameObject seatruckFabricatorModulePrefab = seatruckFabricatorModuleRequest.Result;
         *
         *  _GameObject = UWE.Utils.InstantiateDeactivated(seatruckFabricatorModulePrefab);
         *
         *  _GameObject.SetActive(true);
         *
         *  gameObject.Set(_GameObject);
         * }
         */

        public override IEnumerator GetGameObjectAsync(IOut <GameObject> gameObject)
        {
            AsyncOperationHandle <GameObject> loadRequest_01 = AddressablesUtility.LoadAsync <GameObject>("WorldEntities/Tools/SeaTruckFabricatorModule.prefab");

            yield return(loadRequest_01);

            if (loadRequest_01.Status == AsyncOperationStatus.Failed)
            {
                BZLogger.Error("Cannot find GameObject in Resources folder at path 'WorldEntities/Tools/SeaTruckFabricatorModule.prefab'");
                yield break;
            }

            GameObject seatruckFabricatorModulePrefab = loadRequest_01.Result;

            GameObjectClone = UWE.Utils.InstantiateDeactivated(seatruckFabricatorModulePrefab, null, Vector3.zero, Quaternion.identity);

            SetupScannerModule();

            /*
             * IAssetBundleWrapperCreateRequest bundleRequest = AssetBundleManager.LoadBundleAsync("basegeneratorpieces");
             * yield return bundleRequest;
             * IAssetBundleWrapper bundle = bundleRequest.assetBundle;
             * IAssetBundleWrapperRequest loadRequest_02 = bundle.LoadAssetAsync<GameObject>("Assets/Prefabs/Base/GeneratorPieces/BaseMapRoom.prefab");
             * yield return loadRequest_02;
             * GameObject maproom = loadRequest_02.asset as GameObject;
             */
            AsyncOperationHandle <GameObject> loadRequest_02 = AddressablesUtility.LoadAsync <GameObject>("Assets/Prefabs/Base/GeneratorPieces/BaseMapRoom.prefab");

            yield return(loadRequest_02);

            if (loadRequest_02.Status == AsyncOperationStatus.Failed)
            {
                BZLogger.Error("Cannot find Prefab at path 'Assets/Prefabs/Base/GeneratorPieces/BaseMapRoom.prefab'");
                yield break;
            }

            GameObject maproom = loadRequest_02.Result;

            if (!maproom)
            {
                BZLogger.Debug("Failed to load MapRoom prefab!");
                yield break;
            }

            antenna = UWE.Utils.InstantiateDeactivated(maproom.transform.Find("Map_room_antenna").gameObject, GameObjectClone.transform, Vector3.zero, Quaternion.identity);

            AsyncOperationHandle <GameObject> loadRequest_03 = AddressablesUtility.LoadAsync <GameObject>("Submarine/Build/BatteryCharger.prefab");

            yield return(loadRequest_03);

            GameObject batteryChargerPrefab = loadRequest_03.Result;

            GameObject powerSystemRoot = new GameObject("powerSystemRoot");

            powerSystemRoot.transform.SetParent(GameObjectClone.transform);
            powerSystemRoot.transform.localPosition = new Vector3(-1.06f, -0.20f, 1.66f);
            powerSystemRoot.transform.localRotation = Quaternion.Euler(0, 270, 180);
            powerSystemRoot.transform.localScale    = new Vector3(1.78f, 1.78f, 1.0f);

            powerSystem = UWE.Utils.InstantiateDeactivated(batteryChargerPrefab, powerSystemRoot.transform, Vector3.zero, Quaternion.identity);

            AsyncOperationHandle <GameObject> loadRequest_04 = AddressablesUtility.LoadAsync <GameObject>("Submarine/Build/MapRoomFunctionality.prefab");

            yield return(loadRequest_04);

            GameObject mapRoomFunctionalityPrefab = loadRequest_04.Result;

            scannerUIRoot = new GameObject("scannerRoot");
            scannerUIRoot.transform.SetParent(GameObjectClone.transform, false);
            scannerUIRoot.transform.localScale    = new Vector3(1.14f, 1.14f, 1.14f);
            scannerUIRoot.transform.localPosition = new Vector3(1.37f, 0.07f, 1.60f);
            scannerUIRoot.transform.localRotation = Quaternion.Euler(0, 90, 0);

            scannerUI = UWE.Utils.InstantiateDeactivated(mapRoomFunctionalityPrefab.transform.Find("screen/scannerUI").gameObject, scannerUIRoot.transform, Vector3.zero, Quaternion.identity);

            SetupAntenna();
            SetupScannerUI();
            SetupPowerSystem();

            GameObjectClone.AddComponent <SeaTruckSegmentListener>();

            gameObject.Set(GameObjectClone);

            yield break;
        }
Example #12
0
        static AsyncOperationHandle <IResourceLocator> OnCatalogDataLoaded(AddressablesImpl addressables, AsyncOperationHandle <ContentCatalogData> op, string providerSuffix)
        {
            var data = op.Result;

            addressables.Release(op);
            if (data == null)
            {
                return(addressables.ResourceManager.CreateCompletedOperation <IResourceLocator>(null, new Exception("Failed to load content catalog.").Message));
            }
            else
            {
                if (data.ResourceProviderData != null)
                {
                    foreach (var providerData in data.ResourceProviderData)
                    {
                        LoadProvider(addressables, providerData, providerSuffix);
                    }
                }
                if (addressables.InstanceProvider == null)
                {
                    var prov = data.InstanceProviderData.CreateInstance <IInstanceProvider>();
                    if (prov != null)
                    {
                        addressables.InstanceProvider = prov;
                    }
                }
                if (addressables.SceneProvider == null)
                {
                    var prov = data.SceneProviderData.CreateInstance <ISceneProvider>();
                    if (prov != null)
                    {
                        addressables.SceneProvider = prov;
                    }
                }

                ResourceLocationMap locMap = data.CreateCustomLocator(data.location.PrimaryKey, providerSuffix);
                addressables.AddResourceLocator(locMap, data.localHash, data.location);
                addressables.AddResourceLocator(new DynamicResourceLocator(addressables));
                return(addressables.ResourceManager.CreateCompletedOperation <IResourceLocator>(locMap, string.Empty));
            }
        }
 private void OnLoadAssetDone(AsyncOperationHandle <GameObject> obj)
 {
     Debug.LogWarning($"load {obj.Result} done");
     _prefab = obj.Result;
     _prefab.AddComponent <PlayerMoveController>();
 }
Example #14
0
            public void Init(IResourceLocation location, LoadSceneMode loadMode, bool activateOnLoad, int priority, AsyncOperationHandle <IList <AsyncOperationHandle> > depOp)
            {
                m_DepOp = depOp;
                if (m_DepOp.IsValid())
                {
                    m_DepOp.Acquire();
                }

                m_Location       = location;
                m_LoadMode       = loadMode;
                m_ActivateOnLoad = activateOnLoad;
                m_Priority       = priority;
            }
Example #15
0
 private void OnLoaded(AsyncOperationHandle <Sprite> obj)
 {
     Debug.Log(obj.Result.ToString());
     _sprite.sprite = obj.Result;
 }
Example #16
0
 internal AsyncOperationHandle StartOperation(IAsyncOperation operation, AsyncOperationHandle dependency)
 {
     operation.Start(this, dependency, m_UpdateCallbacks);
     return(operation.Handle);
 }
 public static AsyncOperationHandle <SceneInstance> ReleaseScene(this ISceneProvider provider, ResourceManager resourceManager, AsyncOperationHandle <SceneInstance> sceneLoadHandle, UnloadSceneOptions unloadOptions)
 {
     if (provider is ISceneProvider2)
     {
         return(((ISceneProvider2)provider).ReleaseScene(resourceManager, sceneLoadHandle, unloadOptions));
     }
     return(provider.ReleaseScene(resourceManager, sceneLoadHandle));
 }
Example #18
0
 /// <summary>
 /// Release the operation associated with the specified handle
 /// </summary>
 /// <param name="handle">The handle to release.</param>
 public void Release(AsyncOperationHandle handle)
 {
     handle.Release();
 }
    public IEnumerator SpawnNewSegment()
    {
        if (!m_IsTutorial)
        {
            if (m_CurrentThemeData.zones[m_CurrentZone].length < m_CurrentZoneDistance)
            {
                ChangeZone();
            }
        }

        int segmentUse = Random.Range(0, m_CurrentThemeData.zones[m_CurrentZone].prefabList.Length);

        if (segmentUse == m_PreviousSegment)
        {
            segmentUse = (segmentUse + 1) % m_CurrentThemeData.zones[m_CurrentZone].prefabList.Length;
        }

        AsyncOperationHandle segmentToUseOp = m_CurrentThemeData.zones[m_CurrentZone].prefabList[segmentUse].InstantiateAsync(_offScreenSpawnPos, Quaternion.identity);

        yield return(segmentToUseOp);

        if (segmentToUseOp.Result == null || !(segmentToUseOp.Result is GameObject))
        {
            Debug.LogWarning(string.Format("Unable to load segment {0}.", m_CurrentThemeData.zones[m_CurrentZone].prefabList[segmentUse].Asset.name));
            yield break;
        }
        TrackSegment newSegment = (segmentToUseOp.Result as GameObject).GetComponent <TrackSegment>();

        Vector3    currentExitPoint;
        Quaternion currentExitRotation;

        if (m_Segments.Count > 0)
        {
            m_Segments[m_Segments.Count - 1].GetPointAt(1.0f, out currentExitPoint, out currentExitRotation);
        }
        else
        {
            currentExitPoint    = transform.position;
            currentExitRotation = transform.rotation;
        }

        newSegment.transform.rotation = currentExitRotation;

        Vector3    entryPoint;
        Quaternion entryRotation;

        newSegment.GetPointAt(0.0f, out entryPoint, out entryRotation);


        Vector3 pos = currentExitPoint + (newSegment.transform.position - entryPoint);

        newSegment.transform.position = pos;
        newSegment.manager            = this;

        newSegment.transform.localScale  = new Vector3((Random.value > 0.5f ? -1 : 1), 1, 1);
        newSegment.objectRoot.localScale = new Vector3(1.0f / newSegment.transform.localScale.x, 1, 1);

        if (m_SafeSegementLeft <= 0)
        {
            SpawnObstacle(newSegment);
        }
        else
        {
            m_SafeSegementLeft -= 1;
        }

        m_Segments.Add(newSegment);

        if (newSegmentCreated != null)
        {
            newSegmentCreated.Invoke(newSegment);
        }
    }
Example #20
0
 /// <summary>
 /// Increment reference count of operation handle.
 /// </summary>
 /// <param name="handle">The handle to the resource to increment the reference count for.</param>
 public void Acquire(AsyncOperationHandle handle)
 {
     handle.Acquire();
 }
 void TextureLoaded(AsyncOperationHandle <IList <Texture2D> > obj)
 {
     m_Mat.mainTexture = obj.Result[0];
 }
Example #22
0
        /// <summary>
        /// Create a chain operation to handle dependencies.
        /// </summary>
        /// <typeparam name="TObject">The type of operation handle to return.</typeparam>
        /// <typeparam name="TObjectDependency">The type of the dependency operation.</typeparam>
        /// <param name="dependentOp">The dependency operation.</param>
        /// <param name="callback">The callback method that will create the dependent operation from the dependency operation.</param>
        /// <returns>The operation handle.</returns>
        public AsyncOperationHandle <TObject> CreateChainOperation <TObject, TObjectDependency>(AsyncOperationHandle <TObjectDependency> dependentOp, Func <AsyncOperationHandle <TObjectDependency>, AsyncOperationHandle <TObject> > callback)
        {
            var op = CreateOperation <ChainOperation <TObject, TObjectDependency> >(typeof(ChainOperation <TObject, TObjectDependency>), typeof(ChainOperation <TObject, TObjectDependency>).GetHashCode(), 0, null);

            op.Init(dependentOp, callback);
            return(StartOperation(op, dependentOp));
        }
 public GameObject ProvideInstance(ResourceManager rm, AsyncOperationHandle <GameObject> prefabHandle, InstantiationParameters instantiateParameters)
 {
     return(ProvideInstanceCallback(rm, prefabHandle, instantiateParameters));
 }
Example #24
0
 public void Init(ResourceManager rm, IInstanceProvider instanceProvider, InstantiationParameters instantiationParams, AsyncOperationHandle <GameObject> dependency)
 {
     m_RM                  = rm;
     m_dependency          = dependency;
     m_instanceProvider    = instanceProvider;
     m_instantiationParams = instantiationParams;
 }
 public static IAwaiter <T> GetAwaiter <T>(this AsyncOperationHandle <T> asyncOperationHandle)
 {
     Error.ThrowArgumentDefaultException(asyncOperationHandle, nameof(asyncOperationHandle));
     return(new AsyncOperationHandleAwaiter <T>(asyncOperationHandle));
 }
Example #26
0
 /// <summary>
 /// Release a scene.
 /// </summary>
 /// <param name="sceneProvider">The scene provider.</param>
 /// <param name="sceneLoadHandle">The operation handle used to load the scene.</param>
 /// <returns>An operation handle for the unload.</returns>
 public AsyncOperationHandle <SceneInstance> ReleaseScene(ISceneProvider sceneProvider, AsyncOperationHandle <SceneInstance> sceneLoadHandle)
 {
     if (sceneProvider == null)
     {
         throw new NullReferenceException("sceneProvider is null");
     }
     //           if (sceneLoadHandle.ReferenceCount == 0)
     //               return CreateCompletedOperation<SceneInstance>(default(SceneInstance), "");
     return(sceneProvider.ReleaseScene(this, sceneLoadHandle));
 }
Example #27
0
 private void LoadEventChannel(AsyncOperationHandle <SceneInstance> obj)
 {
     _menuLoadChannel.LoadAssetAsync <LoadEventChannelSO>().Completed += LoadMainMenu;
 }
Example #28
0
        /// <summary>
        /// 下载更新资源
        /// </summary>
        /// <returns></returns>
        internal IEnumerator StartDownLoadAB(Action startOnFinish, List <object> allDownLoad = null)
        {
            StartDownload = true;
            if (allDownLoad == null)
            {
                allDownLoad = m_DownLoadList;
            }
            for (int i = 0; i < allDownLoad.Count; ++i)
            {
                //获取这个m_DownLoadList[i]资源所在的AB包大小,可能多个m_DownLoadList[i]在同一个资源包里面
                //当这个m_DownLoadList[i]资源的AB包下载完成后,这个AB包里其他的m_DownLoadList[i]资源获取
                //GetDownloadSizeAsync的大小会是0,用这个0来判断是否开始下载m_DownLoadList[i]资源的AB包
                AsyncOperationHandle sizeHandle = Addressables.GetDownloadSizeAsync(m_DownLoadList[i]);
                yield return(sizeHandle);

                long totalDownloadSize = (long)sizeHandle.Result;
                if (totalDownloadSize > 0)
                {
                    Debug.Log($"资源:{m_DownLoadList[i]}==所在的AB包要更新的大小{totalDownloadSize}");

                    //先卸载这个资源以前的包
                    //一定要卸载,不然会越更新手机中的资源越多
                    Addressables.ClearDependencyCacheAsync(m_DownLoadList[i]);

                    //再重新下载这个资源包
                    var downloadHandle = Addressables.DownloadDependenciesAsync(m_DownLoadList[i]);
                    while (!downloadHandle.IsDone)
                    {
                        nowLoadSize = downloadHandle.PercentComplete * totalDownloadSize;    //正在下载资源的大小
                        yield return(new WaitForEndOfFrame());
                    }
                    Addressables.Release(downloadHandle);
                    m_AlreadyDownDic.Add(m_DownLoadList[i], totalDownloadSize);

                    nowLoadSize      = 0;
                    alreadyLoadSize += totalDownloadSize;       //已经下载资源的大小

                    Debug.Log($"资源:{m_DownLoadList[i].ToString()}所在的AB包下载完成:{(int)totalDownloadSize}");
                }
                else
                {
                    m_AlreadyDownDic.Add(m_DownLoadList[i], totalDownloadSize);
                }
                Addressables.Release(sizeHandle);
            }

            //下载失败后要重新下载的列表
            List <object> downLoadAgainList = new List <object>();

            for (int i = 0; i < m_DownLoadList.Count; ++i)
            {
                if (!m_AlreadyDownDic.ContainsKey(m_DownLoadList[i]))
                {
                    downLoadAgainList.Add(m_DownLoadList[i]);
                }
            }

            //全部文件都是正确的
            if (downLoadAgainList.Count <= 0)
            {
                if (startOnFinish != null)
                {
                    StartDownload = false;
                    startOnFinish();
                }
                if (LoadOver != null)
                {
                    LoadOver();
                }
            }
            else
            {
                if (m_TryDownCount >= DOWNLOADCOUNT)
                {
                    string allName = "";
                    StartDownload = false;
                    foreach (var item in downLoadAgainList)
                    {
                        allName += item + ";";
                    }
                    Debug.LogError("资源重复下载多次次都失败,请检查资源" + allName);
                    ItemError?.Invoke(allName);
                }
                else
                {
                    m_TryDownCount++;
                    //自动重新下载校验失败的文件
                    m_Startmono.StartCoroutine(StartDownLoadAB(startOnFinish, downLoadAgainList));
                }
            }
        }
Example #29
0
 public AsyncOperationHandle LoadScene(LoadSceneMode loadSceneMode)
 {
     this.operation = Addressables.LoadSceneAsync(this.RuntimeKey, LoadSceneMode.Additive);
     return(this.operation);
 }
    private void OnInstantiateComplete(AsyncOperationHandle <GameObject> asyncOperationHandle)
    {
        asyncOperationHandle.Result.AddComponent <Rigidbody>();

        Debug.Log($"Instantiate complete with status{asyncOperationHandle.Status} IsDone:{asyncOperationHandle.IsDone}");
    }