Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by agentc0re · Jan 09, 2017 at 04:06 PM · coroutinecoroutineswhile-loop

While loop out of control...maybe? I'm not sure. Trying to track Coroutines progress.

I am currently using this from the asset store: Coroutine Manager Pro

Here is my code:

 using UnityEngine;
 using UnityEngine.UI;
 using UnityEngine.SceneManagement;
 using System.Collections;
 //using System.IO;
 using AssetBundles;
 //using System;
 //using System.Collections.Generic;
 //using System.Runtime.Remoting.Channels;
 
 public class NewGameLoadingScene : MonoBehaviour
 {
 
     /// <summary>
     /// Initalizing Variables.
     /// Image for the loading image
     /// Text for loading text (unused by me)
     /// Scenes assetbundle name and scene name
     /// </summary>
     public Image imageComponent;
 
     public Text textComponent;
     public string sceneAssetBundle;
     public string sceneNameTiedToAssetBundle;
 
     /// <summary>
     /// 
     /// </summary>
     //protected void Start()
     IEnumerator Start()
     {
         float startTime = Time.realtimeSinceStartup;
         uint estTime = 10;
         var currentScene = SceneManager.GetActiveScene();
 
         if (imageComponent != null)
         {
             imageComponent.type = Image.Type.Filled;
             imageComponent.fillMethod = Image.FillMethod.Horizontal;
             imageComponent.fillAmount = 0f;
         }
        
         if (textComponent != null)
             textComponent.text = "0%";
 
         ////Init our Assetbundles
         //SetProgress(startTime);
         //yield return StartCoroutine(Initialize());
         //float elapsedTime = (Time.realtimeSinceStartup - startTime)/10;
         ////Start the Async Load
         //SetProgress(elapsedTime);
         //yield return StartCoroutine(AsynchronousLoad(sceneAssetBundle, sceneNameTiedToAssetBundle, true));
         //elapsedTime = (Time.realtimeSinceStartup - startTime)/10;
         //SetProgress(elapsedTime);
         //SceneManager.UnloadSceneAsync(currentScene);
         SetProgress(startTime);
         Debug.Log("Start Time: " + startTime);
         
         float elapsedTime = (Time.realtimeSinceStartup - startTime) / estTime;
         Debug.Log("Elapsed time first call: " + elapsedTime);
         SetProgress(elapsedTime);
 
         var localJobQueue = CM_JobQueue.Make();
         
         localJobQueue.Enqueue(Initialize())
             .Enqueue(AsynchronousLoad(sceneAssetBundle, sceneNameTiedToAssetBundle, true))
             .Start().KillAll(estTime + 3);
         
         while (localJobQueue.running)
         {
             elapsedTime = (Time.realtimeSinceStartup - startTime) / estTime;
             Debug.Log("Elapsed Time in while loop: " + elapsedTime);
             SetProgress(elapsedTime);
             if (!localJobQueue.running)
             {
                 SceneManager.UnloadSceneAsync(currentScene);
                 break;
             }
         }
         
         yield return null;
     }
 
     /// <summary>
     /// 
     /// </summary>
     /// <param name="amount"></param>
     public void SetProgress(float amount)
     {
         if (imageComponent != null)
             imageComponent.fillAmount = amount;
 
         if (textComponent != null)
             textComponent.text = (amount * 100).ToString("0") + "%";
     }
 
     /// <summary>
     /// Initalizing the Source URL. The StreamingAssets folder should be the default place
     /// where you're assetbundles are.
     /// </summary>
     void InitializeSourceURL()
     {
         // Use the following code if AssetBundles are embedded in the project for example via StreamingAssets folder etc:
         AssetBundleManager.SetSourceAssetBundleURL("file://" + Application.streamingAssetsPath + "/");
         // Or customize the URL based on your deployment or configuration
         //AssetBundleManager.SetSourceAssetBundleURL("http://www.MyWebsite/MyAssetBundles");
     }
 
     /// <summary>
     /// Initialize the downloading url and AssetBundleManifest object.
     /// </summary>
     /// <returns></returns>
     protected IEnumerator Initialize()
     {
         // Don't destroy the game object as we base on it to run the loading script.
         DontDestroyOnLoad(gameObject);
 
         InitializeSourceURL();
 
         // Initialize AssetBundleManifest which loads the AssetBundleManifest object.
         var request = AssetBundleManager.Initialize();
 
         if (request != null)
             yield return StartCoroutine(request);
     }
 
     /// <summary>
     /// 
     /// </summary>
     /// <param name="scene"></param>
     /// <returns></returns>
     IEnumerator AsynchronousLoad(string sceneBundle, string sceneName, bool isAditive)
     {
         //yield return null;
 
         //AsyncOperation ao = SceneManager.LoadSceneAsync(sceneName);
         //AsyncOperation ao = AssetBundle.LoadFromFileAsync(Path.Combine(Path.Combine(Application.streamingAssetsPath, Utility.GetPlatformName()), sceneBundle));
 
         //Before we continue check to make sure our request isn't null.
         AssetBundleLoadOperation request = AssetBundleManager.LoadLevelAsync(sceneBundle, sceneName, isAditive);
         if (request == null)
             yield break;
         //ao.allowSceneActivation = false;
         yield return StartCoroutine(request);
 
         //Debug.Log("Entering AO");
 
         //while (!ao.isDone)
         //{
         //    // [0, 0.9] > [0, 1]
         //    //float progress = Mathf.Clamp01(ao.progress / 0.9f);
         //    //Debug.log("Loading progress: " + (progress * 100) + "%");
 
         //    // Loading completed
         //    //Debug.Log("Setting progress in while loop");
         //    SetProgress(ao.progress);
 
         //    if (ao.progress == 0.99f)
         //    {
         //        ao.allowSceneActivation = true;
         //    }
 
         //    yield return null;
         //}
     }
 }

I think in the IEnumerator Start(), where I have that while loop, is causing my problem. Well I know it is because when I comment it out, the coroutines run.

I am trying to monitor the progress of my coroutines, which is why I picked up the asset, so I can can properly SetProgress() to my loading bar. The while loop I was trying to design was just to check if that coroutine queue was running, if so, keep setting the progress for the loading bar. Once progress has stopped, unload the loading bar screen and bam the game starts. :D

Is my logic wrong?

Comment
Add comment · Show 2
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image agentc0re · Jan 08, 2017 at 05:28 AM 0
Share

I know my code is messy right now with a lot of commented out things, but I plan on cleaning that up once I find the solution to my problem! :D

avatar image Pengocat · Jan 09, 2017 at 04:21 PM 2
Share

Place another Yield return null; in the while loop to prevent the execution from stalling. That might fix it.

1 Reply

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by agentc0re · Jan 13, 2017 at 02:06 AM

So the developer go back with me and I was on the right track but just doing a few things wrong. I wasn't adding the jobs to the queue right, in terms of making the running or isRunning method work. I also wasn't sure be he cleared it up that this check must be in LateUpdate. Below is the code that works for me. I hope this can help someone else!

 using UnityEngine;
 using UnityEngine.UI;
 using UnityEngine.SceneManagement;
 using System.Collections;
 using System.IO;
 using AssetBundles;
 
 /// <summary>
 /// 
 /// </summary>
 public class NewGameLoadingScene : MonoBehaviour
 {
 
     /// <summary>
     /// Initalizing Variables.
     /// Image for the loading image
     /// Text for loading text (unused by me)
     /// Scenes assetbundle name and scene name
     /// </summary>
     public Image imageComponent;
 
     public Text textComponent;
     public string sceneAssetBundle;
     public string sceneNameTiedToAssetBundle;
 
     private float startTime;
     private float elapsedTime;
     private float framesProcessed;
     private float framesRemaining;
     private float timeLeft;
 
     bool isQueueRunning;
     bool isInitRunning;
     bool isAsyncRunning;
 
     private CM_Job initJob;
     private CM_Job asyncJob;
 
     Scene currentScene;
 
 
     void Awake()
     {
         SetProgress(0);
         startTime = Time.realtimeSinceStartup;
         startTime = Mathf.Round(startTime);
         currentScene = SceneManager.GetActiveScene();
         elapsedTime = Time.realtimeSinceStartup - startTime;
     }
 
     /// <summary>
     /// 
     /// </summary>
     void Start()
     {
 
         if (imageComponent != null)
         {
             imageComponent.type = Image.Type.Filled;
             imageComponent.fillMethod = Image.FillMethod.Horizontal;
             imageComponent.fillAmount = 0f;
         }
        
         if (textComponent != null)
             textComponent.text = "0%";
 
         initJob = CM_Job.Make(Initialize(), "init");
         asyncJob = CM_Job.Make(AsynchronousLoad(sceneAssetBundle, sceneNameTiedToAssetBundle, true), "asyncLoad");
         CM_JobQueue.Global.Enqueue(initJob).Enqueue(asyncJob).Start();
         
         //Debug.Log("<color=red>Current Scene:</color> " + currentScene.name);
     }
 
     void LateUpdate()
     {
         framesProcessed += Time.frameCount/Time.deltaTime * 0.00001f;
         framesRemaining += Mathf.Abs(1 - framesProcessed);
         /* this is based off of:
          * (TimeTaken / framesProcessed) * framesRemaining = timeLeft
          * so we have
          * (10/100) * 200 = 20 Seconds now 10 seconds go past
          * (20/100) * 200 = 40 Seconds left now 10 more seconds and we process 100 more lines
          * (30/200) * 100 = 15 Seconds and now we all see why the copy file dialog jumps from 3 hours to 30 minutes :-)
          * 
          * pulled from http://stackoverflow.com/questions/473355/calculate-time-remaining/473369#473369
          */
         isQueueRunning = CM_JobQueue.Global.running;
         isInitRunning = initJob.running;
         isAsyncRunning = asyncJob.running;
         if (isQueueRunning || isInitRunning || isAsyncRunning)
         {
             
             elapsedTime = (Time.realtimeSinceStartup - startTime);
             //Debug.Log("Frames Processed, Frames Remaining & Elapsed Time: " + framesProcessed + " / " + framesRemaining + " / " + elapsedTime);
             timeLeft += elapsedTime / framesProcessed * framesRemaining * 0.00001f;
             SetProgress(timeLeft);
             //Debug.Log("Time Left Calculation: " + timeLeft);
         }
         if (!isQueueRunning && !isInitRunning && !isAsyncRunning)
         {
             SetProgress(1);
             SceneManager.UnloadSceneAsync(currentScene);
         }
         //Debug.Log("<color=red>Is Any Queue running in LateUpdate?</color> " + isQueueRunning + " " + isInitRunning + " " + isAsyncRunning);
     }
 
     /// <summary>
     /// 
     /// </summary>
     /// <param name="amount"></param>
     public void SetProgress(float amount)
     {
         if (imageComponent != null)
             imageComponent.fillAmount = amount;
 
         if (textComponent != null)
             textComponent.text = (amount * 100).ToString("0") + "%";
     }
 
     /// <summary>
     /// Initalizing the Source URL. The StreamingAssets folder should be the default place
     /// where you're assetbundles are.
     /// </summary>
     void InitializeSourceURL()
     {
         // Use the following code if AssetBundles are embedded in the project for example via StreamingAssets folder etc:
         AssetBundleManager.SetSourceAssetBundleURL("file://" + Application.streamingAssetsPath + "/");
         // Or customize the URL based on your deployment or configuration
         //AssetBundleManager.SetSourceAssetBundleURL("http://www.MyWebsite/MyAssetBundles");
     }
 
     /// <summary>
     /// Initialize the downloading url and AssetBundleManifest object.
     /// </summary>
     /// <returns></returns>
     public IEnumerator Initialize()
     {
         // Don't destroy the game object as we base on it to run the loading script.
         DontDestroyOnLoad(gameObject);
 
         InitializeSourceURL();
 
         // Initialize AssetBundleManifest which loads the AssetBundleManifest object.
         var request = AssetBundleManager.Initialize();
         if (request != null)
         {
             yield return StartCoroutine(request);
         }
         //Debug.Log("<color=red>Is Any Queue running in INITIALIZE?</color> " + isQueueRunning + " " + isInitRunning + " " + isAsyncRunning);
     }
 
     /// <summary>
     /// 
     /// </summary>
     /// <param name="sceneBundle"></param>
     /// <param name="sceneName"></param>
     /// <param name="isAditive"></param>
     /// <returns></returns>
     public IEnumerator AsynchronousLoad(string sceneBundle, string sceneName, bool isAditive)
     {
         AssetBundleLoadOperation request = AssetBundleManager.LoadLevelAsync(sceneBundle, sceneName, isAditive);
         if (request == null)
             yield break;
         yield return StartCoroutine(request);
         //Debug.Log("<color=red>Is Any Queue running in INITIALIZE?</color> " + isQueueRunning + " " + isInitRunning + " " + isAsyncRunning);
     }
 }
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

Related Questions

When there is a while-loop in a Coroutine, if I have a "yield" within the while-loop, does that mean the Coroutine will be re-entered within the while loop? 1 Answer

How to make a 2D object move smoothly in a random direction for a set amount of time. 2 Answers

StopCoroutine with IEnumerator not working 2 Answers

Coroutine stops after while-loop 1 Answer

NullReferenceException in StartCoroutine 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges