private async void OpenProgressIndicator(IProgressIndicator indicator) { await indicator.OpenAsync(); float timeStarted = Time.time; while (Time.time < timeStarted + loadingTime) { float normalizedProgress = Mathf.Clamp01((Time.time - timeStarted) / loadingTime); indicator.Progress = normalizedProgress; indicator.Message = loadingMessages[Mathf.FloorToInt(normalizedProgress * loadingMessages.Length)]; await Task.Yield(); switch (indicator.State) { case ProgressIndicatorState.Open: break; default: // The indicator was closed return; } } await indicator.CloseAsync(); }
private async Task TestOpenCloseProgressIndicatorAsync(GameObject progressIndicatorObject, IProgressIndicator progressIndicator, float timeOpen = 2f) { // Deactivate the progress indicator progressIndicatorObject.SetActive(false); // Make sure it's closed Assert.True(progressIndicator.State == ProgressIndicatorState.Closed, "Progress indicator was not in correct state on startup: " + progressIndicator.State); // Make sure we can set progress and message progressIndicator.Progress = 0; progressIndicator.Message = "Progress Test"; // Wait for it to open await progressIndicator.OpenAsync(); // Make sure it's actually open Assert.True(progressIndicator.State == ProgressIndicatorState.Open, "Progress indicator was not open after open async call: " + progressIndicator.State); // Make sure we can set its progress and message while open // Also make sure we can set progress to a value greater than 1 without blowing anything up float timeStarted = Time.time; while (Time.time < timeStarted + timeOpen) { progressIndicator.Progress = Time.time - timeStarted; progressIndicator.Message = "Current Time: " + Time.time; await Task.Yield(); } // Wait for it to close await progressIndicator.CloseAsync(); // Make sure it's actually closed Assert.True(progressIndicator.State == ProgressIndicatorState.Closed, "Progress indicator was not closed after close async call: " + progressIndicator.State); }
/// <inheritdoc /> public async Task HideProgressIndicator() { if (TransitionInProgress) { Debug.LogWarning("A scene transition is already in progress. This would interrupt that transition. Taking no action."); return; } if (defaultProgressIndicator == null) { // No need to do anything. return; } using (HideProgressIndicatorPerfMarker.Auto()) { switch (defaultProgressIndicator.State) { case ProgressIndicatorState.Closed: // No need to do anything. return; case ProgressIndicatorState.Closing: while (defaultProgressIndicator.State == ProgressIndicatorState.Closing) { // Wait for progress indicator to be done closing await Task.Yield(); } return; case ProgressIndicatorState.Open: await defaultProgressIndicator.CloseAsync(); return; case ProgressIndicatorState.Opening: while (defaultProgressIndicator.State == ProgressIndicatorState.Opening) { // Wait for it to be done opening, then close it await Task.Yield(); } await defaultProgressIndicator.CloseAsync(); return; } } }
private async void CloseProgressIndicator(IProgressIndicator indicator) { await indicator.AwaitTransitionAsync(); if (indicator.State == ProgressIndicatorState.Open) { await indicator.CloseAsync(); } }
// async task to display the progress of the indicator. See MRTK documentation on progress indicators for more details. private async void OpenProgressIndicator(IProgressIndicator indicator) { await indicator.OpenAsync(); while (doIndicate) { progressIndicator.Progress = progress; await Task.Yield(); } await indicator.CloseAsync(); }
public async void StartProgressBehavior() { if (startedProgressBehavior) { Debug.Log("Can't start until behavior is completed."); return; } startedProgressBehavior = true; IProgressIndicator indicator = progressIndicatorObject.GetComponent <IProgressIndicator>(); indicator.Message = "Preparing for scene operation..."; await indicator.OpenAsync(); Task sceneTask; string progressMessage; // A scene this small will load almost instantly, so we're doing a delay so the indicator is visible float timeStarted = Time.time; while (Time.time < timeStarted + loadDelay) { await Task.Yield(); } if (CoreServices.SceneSystem.IsContentLoaded(sceneToLoad.Name)) { sceneTask = CoreServices.SceneSystem.UnloadContent(sceneToLoad.Name); progressMessage = "Unloading scene {0}"; } else { sceneTask = CoreServices.SceneSystem.LoadContent(sceneToLoad.Name, UnityEngine.SceneManagement.LoadSceneMode.Additive); progressMessage = "Loading scene {0}"; } indicator.Message = progressMessage; while (!sceneTask.IsCompleted) { indicator.Message = string.Format(progressMessage, CoreServices.SceneSystem.SceneOperationProgress * 100); await Task.Yield(); } indicator.Message = "Finished operation"; await indicator.CloseAsync(); startedProgressBehavior = false; }
public async void StartProgressBehavior() { if (progressIndicator.State != ProgressIndicatorState.Closed) { Debug.LogWarning("Can't start progress behavior in this state."); return; } progressIndicator.Message = $"Starting animation..."; progressIndicator.Progress = 0; await progressIndicator.OpenAsync(); animator.SetTrigger("PlayAnimation"); await Task.Yield(); // Wait for animation to START playing bool playingAnimation = false; while (!playingAnimation) { var stateInfo = animator.GetCurrentAnimatorStateInfo(0); playingAnimation = stateInfo.IsName(animationName); progressIndicator.Message = $"Waiting for animation to start..."; await Task.Yield(); } // Wait for animation to STOP playing while (playingAnimation) { var stateInfo = animator.GetCurrentAnimatorStateInfo(0); playingAnimation = stateInfo.IsName(animationName); if (playingAnimation) { progressIndicator.Message = $"Waiting for animation to finish..."; progressIndicator.Progress = stateInfo.normalizedTime; } await Task.Yield(); } progressIndicator.Progress = 1; progressIndicator.Message = $"Finished with animation..."; await progressIndicator.CloseAsync(); }
private async void HandleButtonClick(IProgressIndicator indicator) { // If the indicator is opening or closing, wait for that to finish before trying to open / close it // Otherwise the indicator will display an error and take no action await indicator.AwaitTransitionAsync(); switch (indicator.State) { case ProgressIndicatorState.Closed: OpenProgressIndicator(indicator); break; case ProgressIndicatorState.Open: await indicator.CloseAsync(); break; } }
public async void StartProgressBehavior() { if (tokenSource != null) { Debug.LogWarning("Can't start progress behavior in this state."); return; } progressIndicator.Message = "Opening..."; await progressIndicator.OpenAsync(); tokenSource = new CancellationTokenSource(); Task asyncMethod = AsyncMethod(tokenSource.Token); progressIndicator.Message = "Waiting for async method to complete..."; while (!asyncMethod.IsCompleted) { await Task.Yield(); } tokenSource = null; progressIndicator.Message = "Closing..."; await progressIndicator.CloseAsync(); }
/// <inheritdoc /> public async Task DoSceneTransition(IEnumerable <Func <Task> > sceneOperations, IProgressIndicator progressIndicator = null) { if (TransitionInProgress) { throw new Exception("Attempting to do a transition while one is already in progress."); } #region Transition begin TransitionInProgress = true; OnTransitionStarted?.Invoke(); if (progressIndicator == null && sceneTransitionServiceProfile.UseDefaultProgressIndicator) { // If we haven't been given a progress indicator, and we're supposed to use a default // find / create the default progress indicator CreateDefaultProgressIndicator(); progressIndicator = defaultProgressIndicator; } if (UseFadeColor) { await FadeOut(); } if (progressIndicator != null) { await progressIndicator.OpenAsync(); } #endregion #region Task execution // Make sure we're on the main thread foreach (Func <Task> sceneOperation in sceneOperations) { await sceneOperation(); } #endregion #region Transition end // If we used a progress indicator, close it if (progressIndicator != null) { await progressIndicator.CloseAsync(); } if (UseFadeColor) { await FadeIn(); } TransitionInProgress = false; OnTransitionCompleted?.Invoke(); #endregion }
/// <summary> /// Queries the Litecoin Pool REST API asynchronously via https request and updates the slate with the current stats. /// </summary> /// <returns>The asynchronous task which should be awaited the result of which is the http response message.</returns> public async void QueryRESTAPI() { // If we're already in the middle of querying the REST API, don't query it again. if (updating) { // Set the refresh timer back to 0. refreshTimer = 0f; return; } updating = true; if (Status.gameObject.activeSelf) { // Allow a brief moment so the status text is viewable on the first run or after an error. await Task.Delay(1000); } // Don't show the progress indicator on the first run (the mining stats will not be active on the first run or after an error). if (MiningStats.gameObject.activeSelf) { QueueOnUpdate(() => { ProgressIndicator.SetActive(true); }); await indicator.AwaitTransitionAsync(); UpdateProgressIndicator(); } client.CancelPendingRequests(); // Get the currently selected currency from the currency hand menu. currency = currencyHandMenu.GetComponent <CurrencySelection>().Currency; HttpResponseMessage response = await client.GetAsync(client.BaseAddress).ConfigureAwait(false); if (response.IsSuccessStatusCode) { JObject jobject = (JObject)JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result); QueueOnUpdate(() => { // The hash rate is returned as kilohash. Convert it to a size appropriate unit of measure formatted for easy reading. HashRate.text = $"{FormatHash((decimal)jobject["user"]["hash_rate"] * 1000, 2)}/s"; }); QueueOnUpdate(() => { // Format the paid rewards to two decimal points and include a currency conversion for the currently selected currency. PaidRewards.text = $"{Math.Round((decimal)jobject["user"]["paid_rewards"], 2)} LTC ({ConvertCurrency((decimal)jobject["user"]["paid_rewards"], (decimal)jobject["market"][currency])})"; }); QueueOnUpdate(() => { // Format the unpaid rewards to six decimal points and include a currency conversion for the currently selected currency. UnpaidRewards.text = $"{Math.Round((decimal)jobject["user"]["unpaid_rewards"], 6)} LTC ({ConvertCurrency((decimal)jobject["user"]["unpaid_rewards"], (decimal)jobject["market"][currency])})"; }); QueueOnUpdate(() => { // The total work is returned as hash (lowest unit of measure). Convert it to a size appropriate unit of measure formatted for easy reading. TotalWork.text = FormatHash((decimal)jobject["user"]["total_work"] / 10, 0); }); QueueOnUpdate(() => { Blocks.text = (string)jobject["user"]["blocks_found"]; }); QueueOnUpdate(() => { // Format the price per share ratio as a percentage with no decimal points. Ratio.text = $"{Math.Round((decimal)jobject["pool"]["pps_ratio"] * 100, 0)}%"; }); QueueOnUpdate(() => { // Format the network difficulty to five decimal points and add standard numerical comma notation. Difficulty.text = Math.Round((decimal)jobject["network"]["difficulty"], 5).ToString("#,##0.00000"); }); QueueOnUpdate(() => { Status.gameObject.SetActive(false); MiningStats.SetActive(true); }); } else { QueueOnUpdate(() => { MiningStats.SetActive(false); Status.gameObject.SetActive(true); ProgressIndicator.SetActive(false); Status.text = "Error communicating with litecoinpool.org"; }); // Allow a brief moment so the status text to be viewable. await Task.Delay(2000); } updating = false; await indicator.AwaitTransitionAsync(); await indicator.CloseAsync(); }
private async void HandleIndicatorStop(IProgressIndicator indicator) { await indicator.CloseAsync(); }