Search Unity

Looping a Function

Discussion in 'Scripting' started by yangmeng, Sep 26, 2007.

  1. yangmeng

    yangmeng

    Joined:
    Dec 5, 2006
    Posts:
    573
    Is there an easy way to make a function loop? For example, one line of code at the end of the function that basically says "repeat"?
    I've used this kind of code:
    Code (csharp):
    1. for (t=0;t<50;t++) {
    2. }
    But is there a better way, and one that loops infinitely?
     
  2. forestjohnson

    forestjohnson

    Joined:
    Oct 1, 2005
    Posts:
    1,370
    What you don't want to do is loops like this:


    Code (csharp):
    1.  
    2. function Start ()
    3. {
    4.     Loop();
    5. }
    6.  
    7. function Loop ()
    8. {
    9.     // do stuff
    10.     yield;
    11.     Loop();
    12. }
    13.  

    As they leak memory very quickly and lead to crashes.

    The official way to create a loop is like this:


    Code (csharp):
    1.  
    2. function Start ()
    3. {
    4.     Loop();
    5. }
    6.  
    7. function Loop ()
    8. {
    9.     while(true)
    10.     {
    11.         // do stuff
    12.         yield;
    13.     }
    14. }
    15.  
     
  3. yangmeng

    yangmeng

    Joined:
    Dec 5, 2006
    Posts:
    573
    "while(true)", eh? Short, easy, it works...
    Perfect, thanks!