Search Unity

Time In While Loop Not Working

Discussion in 'Scripting' started by darandomturtle786, Aug 5, 2022.

  1. darandomturtle786

    darandomturtle786

    Joined:
    Apr 2, 2020
    Posts:
    1
    This loop should make the slider value increade over time(in this case 3 seconds) however it basically jumps to 3 very fast. idk whats wrong


    Code (CSharp):
    1.     private IEnumerator LerpSlider(Slider slider, float time)
    2.     {
    3.         float timeScale = 0;
    4.         float speed = 1/time;
    5.         while (timeScale < 1)
    6.         {
    7.             timeScale += Time.deltaTime * speed;
    8.             slider.value = Mathf.Lerp(0f, 3f, timeScale);
    9.             Debug.Log(slider.value);
    10.         }
    11.         slider.gameObject.SetActive(false);
    12.         yield return null;
    13.     }
     
  2. RadRedPanda

    RadRedPanda

    Joined:
    May 9, 2018
    Posts:
    1,647
    While loops won't pause in between iterations, you need to
    yield return null
    inside of the loop for it to wait until the next update.
     
    Bunny83 likes this.
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,686
    Unity locks up solid until you return from your code. Therefore all X iterations of however long it takes to count timeScale up to 1 will occur all in one frame.

    If you had set timeScale to zero, you would have locked Unity up solid and you would have to force-quit.

    You are not the app. Your code is not the app. Unity is the app. Unity is the code. Your code may get called at Unity's convenience and discretion, as long as you follow all the "please call my code" rules.

    Here is some timing diagram help:

    https://docs.unity3d.com/Manual/ExecutionOrder.html

    Said another way:

    https://forum.unity.com/threads/res...-problem-when-using-ioc.1283879/#post-8140583
     
    Last edited: Aug 6, 2022
    Bunny83 likes this.