Search Unity

For Loop is controlling all elements of an x[i] array

Discussion in 'Scripting' started by WDElrex, Jan 18, 2019.

  1. WDElrex

    WDElrex

    Joined:
    Oct 27, 2016
    Posts:
    5
    Hi there,

    I have a scene that is basically a 360 panoramic viewer with some added functionality.

    I am using circle image fills as progress bars. In some of the nodes, there are multiple other nodes to jump to. In my script:

    variable for context: public Image[] loadingBarFloor;

    Code (CSharp):
    1.     //Start load countdown & loading animation
    2.     void TriggerHotSpot(int hsNumber)
    3.     {
    4.         for (int i = 0; i < hotspots.Length; i++)
    5.         {
    6.             loadIcon.transform.localScale = new Vector3(1.0f, 1.0f, 1.0f);
    7.             Debug.Log(loadTimer);
    8.             transform.localScale = originalScale * 0.5f;
    9.             loadTimer += Time.deltaTime / speed;
    10.             loadingBarFloor[i].fillAmount = loadTimer / 2;
    11.             loadingBarText[i].GetComponent<Text>().text = (loadTimer * 100).ToString("#") + "%";
    12.             if (loadTimer >= 1.0f)
    13.             {
    14.                 loadTimer += loadScaleSpeed * Time.deltaTime;
    15.                 StartCoroutine(ChangeNode(hsNumber));
    16.                 loadingBarText[i].text = ("Done!");
    17.             }
    18.             loadingBarFloor[i].fillAmount = loadTimer;
    19.         }
    20.     }
    I am seeing every progress bar fill instead of just the current one in the array. I only want the current image fill to happen.

    Any help is greatly appreciated, thanks!
     
  2. WallaceT_MFM

    WallaceT_MFM

    Joined:
    Sep 25, 2017
    Posts:
    394
    If you want to fill each bar one after the other, you need to make a coroutine that does that instead of this approach. This will start a coroutine for each element in the array all on the same frame. You likely want do something like this:
    Code (csharp):
    1. private IEnumerator LoadRoutine()
    2. {
    3.    for(int i = 0; i < hotspots.Length; i++)
    4.    {
    5.       float timer = 0;
    6.       while(timer < 1.0f) // While the timer isn't done
    7.       {
    8.          loadingBarFloor[i].fillAmount = timer;
    9.          yield return null;
    10.          timer += Time.deltaTime * speedFactor;
    11.       }
    12.    }
    13. }
    That's not functional code, but hopefully gets the idea across.
     
  3. WDElrex

    WDElrex

    Joined:
    Oct 27, 2016
    Posts:
    5
    Success, anyway a mod can delete this?
     
  4. JeffDUnity3D

    JeffDUnity3D

    Joined:
    May 2, 2017
    Posts:
    14,446
    We don't delete posts so other users can benefit from the lessons learned.
     
    Joe-Censored likes this.