Search Unity

How Can I Use Time in a For Loop?

Discussion in 'Scripting' started by Chris-Ramer, Apr 23, 2016.

  1. Chris-Ramer

    Chris-Ramer

    Joined:
    Dec 9, 2015
    Posts:
    45
    I know it sounds like a dumb question, but it's been bothering me for some time now.

    I know how to use a for loop, but I don't know how to use it with Unity's time scale. My problem is this:

    I need to do a block of code for randMovementTime which is a float variable created and assigned a Random.Range value in the Awake function. So the for loop would look like this:

    Code (JavaScript):
    1. for (i = 0; i > randMovementTime; statement3)
    2. {
    3.   // Block of code goes here...
    4. }
    I don't know how to increment i in statement 3 at the rate of Unity's time scale to make it equal randMovementTime.

    To put it simply: I want to know how to do a for loop for a certain amount of time.

    i would have to be time, but any version of time would be the time since level load or time since startup, but I need the time since the for loop was last triggered, so i needs to start at 0 and be incremented at the rate of the time since the for loop was last triggered.

    Any help is greatly appreciated!

    EDIT: I am using this for loop in the Update function, so no coroutines.

    - Chris
     
    Last edited: Apr 23, 2016
  2. Chris-Ramer

    Chris-Ramer

    Joined:
    Dec 9, 2015
    Posts:
    45
    I have tried to workaround this problem, but by doing so I have come across a smaller problem.

    My workaround was to call a function from within the update function. My code went as follows:

    Code (JavaScript):
    1. function Update ()
    2. {
    3.   if (canMove == true && playerIsDead == false)
    4.   {
    5.     Movement ();
    6.   }
    7. }
    8.  
    9. function Movement ()
    10. {
    11.   while (moveDown == true)
    12.   {
    13.     transform.Translate (0, -Time.fixedDeltaTime * randSpeed, 0);
    14.  
    15.     yield WaitForSeconds (randMovementTime);
    16.     moveDown = false;
    17.     moveUp = true;
    18.  
    19.     break;
    20.   }
    21.  
    22.   while (moveUp == true)
    23.   {
    24.     transform.Translate (0, Time.fixedDeltaTime * randSpeed, 0);
    25.  
    26.     yield WaitForSeconds (randMovementTime);
    27.     moveUp = false;
    28.     moveDown = true;
    29.  
    30.     break;
    31.   }
    32. }
    The problem I had with the above code was that at normal speed, the object would move up more than it would move down. But it works fine when I do it frame-by-frame.