Search Unity

Why is my loop not working?

Discussion in 'Scripting' started by reset, Jul 15, 2009.

  1. reset

    reset

    Joined:
    May 22, 2009
    Posts:
    393
    This script is attached to an model - the Label seems to update only once and the model moves to one vector and stays there - is not my For loop working?

    var rad;

    function Update () {
    mover();
    }

    function mover () {
    for (i=0;i<360;i++){
    rad = i * Mathf.Deg2Rad;
    transform.position.x = 50*Mathf.Sin(rad);
    transform.position.y = 50*Mathf.Cos(rad);
    }
    }

    function OnGUI () {
    GUI.Label (Rect (0, 0, 100, 20), rad.ToString());
    }
     
  2. CoherentInk

    CoherentInk

    Joined:
    Jul 16, 2006
    Posts:
    216
    Your script is going to run through the entire range in one frame. Just add a yield statement at the end of your for loop and it should all work fine.
     
  3. reset

    reset

    Joined:
    May 22, 2009
    Posts:
    393
    thanks - but where would I place it in my script?

    I put it the loop - it waited 5 second then just went nuts. See below

    How do I make it update every frame? Like Delta time?



    function mover () {
    for (i=0;i<360;i++){
    rad = i * Mathf.Deg2Rad;
    transform.position.x = 50*Mathf.Sin(rad);
    transform.position.y = 50*Mathf.Cos(rad);
    yield new WaitForSeconds(5);
    }
    }
     
  4. GargerathSunman

    GargerathSunman

    Joined:
    May 1, 2008
    Posts:
    1,572
    You're calling it every frame, but having it go through all 360 degrees at the same time. As such, you're going to have LOTS of problems.

    You're better off calling it once in start and replacing the WaitForSeconds for a plain yield.

    In order to make it keep looping, you'd just have to have a while (true) loop outside the for loop.
     
  5. Maker16

    Maker16

    Joined:
    Mar 4, 2009
    Posts:
    779
    Or, you can scrap the loop, track you angle in a variable, increment it every frame, and set it to 0 after it hits 360. Call mover() if whichever update loop you were using.

    Code (csharp):
    1.  
    2. var i : int = 0;  //of course, I wouldn't recommend
    3.                   //using 'i' as your variable name
    4.  
    5. function mover ()
    6. {
    7.    if(i>360)
    8.       i = 0;
    9.  
    10.    rad = i * Mathf.Deg2Rad;
    11.    transform.position.x = 50*Mathf.Sin(rad);
    12.    transform.position.y = 50*Mathf.Cos(rad);
    13.  
    14.    i++;  //if 'i' is anything but int, it may
    15.          //be better to use: i += 1;
    16. }
    17.