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. :smiley:

Is my logic wrong?

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);
    }
}