public IEnumerator NextFrame2() => UniTask.ToCoroutine(async() => { await UniTask.Yield(PlayerLoopTiming.PreUpdate); var frame = Time.frameCount; await UniTask.NextFrame(); Time.frameCount.Should().Be(frame + 1); });
/// <summary> /// Async Find /// </summary> /// <param name="search">LobbySearch</param> /// <param name="localUserId">Login user id</param> /// <returns>Task</returns> public static async UniTask <LobbySearchFindCallbackInfo> Find(this LobbySearch search, ProductUserId localUserId) { var op = new LobbySearchFindOptions { LocalUserId = localUserId }; LobbySearchFindCallbackInfo info = null; search.Find(op, null, e => { info = e; }); while (info == null || info.ResultCode == Result.OperationWillRetry) { if (info != null) { Debug.LogError($"error {DebugTools.GetClassMethodName()}:{info.ResultCode}"); info = null; } await UniTask.NextFrame(); } if (info.ResultCode == Result.Success) { return(info); } Debug.LogError($"error {DebugTools.GetClassMethodName()}:{info.ResultCode}"); return(null); }
/// <summary> /// 非同期 Login /// </summary> /// <param name="auth">AuthInterface</param> /// <param name="type">ログイン種別</param> /// <param name="id">ID</param> /// <param name="token">トークン</param> /// <returns>タスク</returns> public static async UniTask <LoginCallbackInfo> Login(this AuthInterface auth, LoginCredentialType type, string id, string token) { var op = new LoginOptions(); op.Credentials = new Credentials { Type = type, Id = id, Token = token, }; LoginCallbackInfo info = null; auth.Login(op, null, e => { info = e; }); while (info == null) { await UniTask.NextFrame(); } if (info.ResultCode == Result.Success) { return(info); } Debug.LogError($"error {DebugTools.GetClassMethodName()}:{info.ResultCode}"); return(null); }
/// <summary> /// Async JoinLobby /// </summary> /// <param name="lobby">LobbyInterface</param> /// <param name="lobbyDetailsHandle">Lobby detail</param> /// <param name="localUserId">Login user id</param> /// <returns>Task</returns> public static async UniTask <JoinLobbyCallbackInfo> JoinLobby(this LobbyInterface lobby, LobbyDetails lobbyDetailsHandle, ProductUserId localUserId) { var joinOp = new JoinLobbyOptions { LobbyDetailsHandle = lobbyDetailsHandle, LocalUserId = localUserId }; JoinLobbyCallbackInfo info = null; lobby.JoinLobby(joinOp, null, e => { info = e; }); while (info == null) { await UniTask.NextFrame(); } if (info.ResultCode == Result.Success) { return(info); } Debug.LogError($"error {DebugTools.GetClassMethodName()}:{info.ResultCode}"); return(null); }
private static async UniTask PlayInternal <T>(IAnimator <T> animator, ITranslator <T> translator, IScheduler scheduler, CancellationToken cancellationToken, SkipToken skipToken) { if (scheduler == default) { scheduler = DefaultScheduler; } var time = 0f; var playState = Application.isPlaying; while (!cancellationToken.IsCancellationRequested && !skipToken.IsSkipRequested && translator.Alive && playState == Application.isPlaying) { var(t, used) = animator.Update(time); translator.Update(t); if (used < time) { break; } await UniTask.NextFrame(scheduler.UpdateTiming, cancellationToken); time += scheduler.DeltaTime; } if (!translator.Alive) { throw new OperationCanceledException("!translator.Alive"); } cancellationToken.ThrowIfCancellationRequested(); if (skipToken.IsSkipRequested) { var(t, _) = animator.Update(float.MaxValue); translator.Update(t); } }
/// <summary> /// カメラ映像をスクリーンショットとして保存する /// </summary> private async UniTask TakeScreenShotAsync(CancellationToken ct) { _camera.enabled = true; await UniTask.NextFrame(cancellationToken : ct); _camera.enabled = false; // GPUからのデータ取得を待つ // AsyncGPUReadbackRequest 型が戻ってくる var req = await AsyncGPUReadback.Request(_renderTexture, 0) .WithCancellation(ct); var rawByteArray = req.GetData <byte>(); // RenderTextureの内容をPNGに変換 var png = ImageConversion.EncodeNativeArrayToPNG( rawByteArray, _renderTexture.graphicsFormat, (uint)_renderTexture.width, (uint)_renderTexture.height); var bytes = png.ToArray(); png.Dispose(); await UniTask.Run(() => File.WriteAllBytes("screenshot.png", bytes)); }
/// <summary> /// 非同期 Login /// </summary> /// <param name="type">ログイン種別</param> /// <param name="id">ID</param> /// <param name="token">トークン</param> /// <returns>タスク</returns> public static async UniTask <LoginCallbackInfo> Login(this ConnectInterface conn, string token, ExternalCredentialType type) { var op = new LoginOptions { Credentials = new Credentials { Token = token, Type = type, }, }; LoginCallbackInfo info = null; conn.Login(op, null, e => { info = e; }); while (info == null) { await UniTask.NextFrame(); } if (info.ResultCode == Result.Success) { return(info); } Debug.LogError($"error {DebugTools.GetClassMethodName()}:{info.ResultCode}"); return(null); }
private async UniTask UnloadPreviousState(CancellationToken token) { var unloadPercentage = 0.45f; // 0.45 for unload, 0.45 for load, 0.1 for buffer var scenes = FilterScenesToUnload(); if (scenes.Count <= 0) { Debug.Log($"[{GetType().Name}] No scene to unload.."); await UniTask.NextFrame(cancellationToken : token); _loadingProgress.Value += unloadPercentage; return; } var sceneCountInv = unloadPercentage / scenes.Count; foreach (var scene in scenes) { var progress = new Progress <float>(value => _loadingProgress.Value = Mathf.Min(0.9f, _loadingProgress.Value + value * sceneCountInv)); await SceneManager.UnloadSceneAsync(scene.ToString()) .ToUniTask(progress, cancellationToken: token); } }
/// <summary> /// Async CreateLobby /// </summary> /// <param name="lobby">LobbyInterface</param> /// <param name="localUserId">Login user id</param> /// <param name="maxLobbyMembers">Max member count</param> /// <param name="permissionLevel">Public settings, etc.</param> /// <returns>Task</returns> public static async UniTask <CreateLobbyCallbackInfo> CreateLobby(this LobbyInterface lobby, ProductUserId localUserId, uint maxLobbyMembers, LobbyPermissionLevel permissionLevel) { var lobbyOp = new CreateLobbyOptions { LocalUserId = localUserId, MaxLobbyMembers = maxLobbyMembers, PermissionLevel = permissionLevel, }; CreateLobbyCallbackInfo info = null; lobby.CreateLobby(lobbyOp, null, e => { info = e; }); while (info == null) { await UniTask.NextFrame(); } if (info.ResultCode == Result.Success) { return(info); } Debug.LogError($"error {DebugTools.GetClassMethodName()}:{info.ResultCode}"); return(null); }
private async UniTask WaitForMoveEnd() { while (IsMoving.Value == MovingStatus.Moving) { await UniTask.NextFrame(); } }
private async UniTask WaitForClicker() { while (3 > click) { await UniTask.NextFrame(); } }
private async void OnStonePushed(Vector3Int origin, Vector3Int destination) { _waterTilemap.SetTile(destination, null); await UniTask.NextFrame(); GameEvents.LayoutChanged?.Invoke(origin); }
private async UniTaskVoid initObj() { setupEarly(); await UniTask.NextFrame(initObjCts.Token); setup(); await UniTask.NextFrame(initObjCts.Token); setupLate(); }
private async UniTask WaitForARSessionReady() { Debug.Log($"Start WaitFor: {ARSession.state}"); while (ARSession.state != ARSessionState.SessionTracking) { Debug.Log($"Waiting: {ARSession.state}"); await UniTask.NextFrame(); } }
private async UniTask Queue(AudioClip clip) { while (source.isPlaying) { await UniTask.NextFrame(); } source.clip = clip; source.Play(); }
private async UniTaskVoid Initialize() { var token = this.GetCancellationTokenOnDestroy(); await UniTask.WhenAll( SceneManager.LoadSceneAsync(SceneNamesEnumCore.Statics.ToString(), LoadSceneMode.Additive).ToUniTask(cancellationToken: token), SceneManager.LoadSceneAsync(SceneNamesEnumCore.SplashScreen.ToString(), LoadSceneMode.Additive).ToUniTask(cancellationToken: token)); await UniTask.NextFrame(cancellationToken : token); SceneManager.UnloadSceneAsync(SceneNamesEnumCore.Boot.ToString()); }
private async UniTaskVoid SmoothResetRotation(Quaternion startRotation) { var elapsed = 0f; float testDuration = 0.5f; while (elapsed < testDuration) { elapsed += Time.deltaTime; cubeRotator.localRotation = Quaternion.Slerp(startRotation, Quaternion.identity, resetAnimationCurve.Evaluate(elapsed / testDuration)); await UniTask.NextFrame(); } }
// todo 最开始加载的task完成后立即unload,会导致task取出的ab为null async UniTask <T> WaitTask <T>(UniTask <T> task, IProgress <float> progress, CancellationToken token) { while (task.Status != UniTaskStatus.Succeeded) { if (task.Status == UniTaskStatus.Canceled || task.Status == UniTaskStatus.Faulted) { throw new OperationCanceledException(); } token.ThrowIfCancellationRequested(); await UniTask.NextFrame(token); } progress?.Report(1); return(await task); }
async UniTask NextFrame() { await UniTask.WaitForEndOfFrame(); Debug.Log("WaitforEndOfFrame"); await UniTask.Yield(); Debug.Log("Yield");// nextFrame和yield有区别,nextframe一定是下一帧,yield不一定是下一帧。 await UniTask.NextFrame(); Debug.Log("NextFrame"); await UniTask.WaitForFixedUpdate(); Debug.Log("WaitForFixedUpdate"); }
private async UniTask ProcessOffset(CancellationToken token) { // hold loading progress as long as loadBufferTime. -> loading screen will stay visible. var bufferMultiplier = 0.1f / Mathf.Max(0.1f, ActiveState.loadBufferTime); while (_loadingProgress.Value < 1) { await UniTask.NextFrame(cancellationToken : token); var delta = Time.deltaTime * bufferMultiplier; _loadingProgress.Value += delta; } _loadingProgress.Value = 1f; }
public async UniTask PlayAnimation(CancellationToken cancellationToken) { var bound = (-_canvasResolution.x / 2 - _textSize.x / 2) * 1.5f; while (!cancellationToken.IsCancellationRequested) { if (_rectTransform.anchoredPosition.x < bound) { return; } _rectTransform.anchoredPosition += new Vector2(-_flowingSpeedPerSec * Time.deltaTime, 0); await UniTask.NextFrame(PlayerLoopTiming.Update, cancellationToken); } }
private async UniTask Fade(Color startColor, Color endColor, float duration, bool leaveOn = false) { faderImage.gameObject.SetActive(true); var elapsed = 0f; while (elapsed < duration) { elapsed += Time.deltaTime; faderImage.color = Color.Lerp(startColor, endColor, elapsed / duration); await UniTask.NextFrame(); } faderImage.gameObject.SetActive(leaveOn); }
public async UniTask Wait() { while (true) { if (UnityUtility.IsNull(this)) { break; } if (!UnityUtility.IsActive(gameObject)) { break; } await UniTask.NextFrame(); } }
public virtual void OnDisable() { if (disableDetect) { return; } disableDetect = true; //下個frame才停止subscribe 避免同frame瞬間開關觸動 UniTask.NextFrame(PlayerLoopTiming.EarlyUpdate).ToObservable().Subscribe(x => { if (!isActiveAndEnabled) { Dispose(); } disableDetect = false; }); }
private async UniTaskVoid CheckCondition() { var token = this.GetCancellationTokenOnDestroy(); await UniTask.NextFrame(cancellationToken : token); if (_activeGrid.Completed) { _gameplayState.Value = _activeLevel == _levelList.Count - 1 ? GameplayStateEnum.AllClear : GameplayStateEnum.Win; if (_activeLevel == _levelList.Count - 1) { _activeLevel.Value = 0; } return; } _gameplayState.Value = GameplayStateEnum.Drop; }
private async UniTaskVoid CheckAvailableMove(CancellationToken token, bool firstCheck = false) { await UniTask.NextFrame(cancellationToken : token); _moveCheck.Clear(); _availableMove = CheckAvailableMoves(_cubeIndex.Value, _moveCheck, _cubeBase.localRotation); if (firstCheck) { await UniTask.NextFrame(cancellationToken : token); } if (_availableMove == 0 && (!_activeCube.IsCompleted || firstCheck)) { _gameplayState.Value = GameplayStateEnum.Lose; } }
private async UniTask SwitchWindowWithAnimationAsync(RectTransform current, RectTransform next) { // 0.5秒で切り替えるので、それぞれ0.25秒で1->0, 0->1のスケール変換をする。 var startTime = Time.time; // 秒 var min = new Vector3(1f, 0, 1); var normal = new Vector3(1f, 1f, 1); current.localScale = normal; next.localScale = min; float timeSpan = 0.25f; while (Time.time < startTime + timeSpan) { var delta = Time.time - startTime; var scale = Vector3.Lerp(normal, min, delta / timeSpan); current.localScale = scale; await UniTask.NextFrame(PlayerLoopTiming.Update); } current.localScale = min; current.gameObject.SetActive(false); next.gameObject.SetActive(true); var startTime2 = Time.time; // 秒 while (Time.time < startTime2 + timeSpan) { var delta = Time.time - startTime2; var scale = Vector3.Lerp(min, normal, delta / timeSpan); next.localScale = scale; await UniTask.NextFrame(PlayerLoopTiming.Update); } next.localScale = normal; }
public async UniTask LoadHTML(string html, string url = null) { await Initialize(); await OnLoad(url); if (webViewContent != null) { await webViewContent.LoadHTML(html, url); } if (onLoad != null) { onLoad.OnNext(Unit.Default); } await UniTask.NextFrame(); }
private async void Start() { _connectButton.enabled = false; var server = await ServiceLocator.GetServiceAsync <IServer <string> >(); _connectButton.enabled = true; _viewModel = new ConnectionSettingUiViewModel(server); _connectButton .onClick .AsObservable() .Subscribe(_ => { this.OnClickConnectionButton().Forget(); }).AddTo(this); _transparentButton.onClick .AsObservable() .Subscribe(_ => { this.OnClickTransparentButton(); }).AddTo(this); _closeButton.onClick .AsObservable() .Subscribe(_ => this.Close().Forget()) .AddTo(this); _minimizeButton.onClick .AsObservable() .Subscribe(_ => this.SwitchWindow().Forget()); _minimumWindow.OnDoubleClick() .Subscribe(_ => this.SwitchWindow().Forget()); _flowingTextSettings = await ServiceLocator.GetServiceAsync <IFlowingTextSettings>(); _fontSizeSlider.onValueChanged .AsObservable() .Subscribe(this.OnFontSizeChange) .AddTo(this); await UniTask.NextFrame(); _flowingTextSettings.FontSize = _fontSizeSlider.value; _minimumWindow.gameObject.SetActive(false); }
private async UniTask OnApplicationStateChanged(ApplicationStateEnum newApplicationState, CancellationToken token) { if (_isLoading) { return; } // necessary to let _applicationState value to be correctly assigned await UniTask.NextFrame(cancellationToken : token); // initialize load _isLoading.Value = true; _loadingProgress.Value = 0; // wait for fade if (_shouldFade) { await UniTask.Delay(TimeSpan.FromSeconds(_fadeDuration), cancellationToken : token); } // unload/load scenes await UnloadPreviousState(token); await LoadCurrentState(token); SetActiveScene(); await UniTask.NextFrame(cancellationToken : token); GC.Collect(); await UniTask.NextFrame(cancellationToken : token); Shader.WarmupAllShaders(); await UniTask.NextFrame(cancellationToken : token); // wait for load buffer time await ProcessOffset(token); PrevState = _cachedConfigs[newApplicationState]; _isLoading.Value = false; }