Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

How to simplify this code

Discussion in 'Scripting' started by ilyamep, Jul 7, 2015.

  1. ilyamep

    ilyamep

    Joined:
    Feb 21, 2015
    Posts:
    12
    How can I simplify this IEnumerator where I want to call myFunction every 2 sec, but only 7 times?
    Sorry for my bad English.

    Code (CSharp):
    1. IEnumerator myIEnumerator (){
    2.     myFunction();
    3.     yield return new WaitForSeconds(2);
    4.     myFunction();
    5.     yield return new WaitForSeconds(2);
    6.     myFunction();
    7.     yield return new WaitForSeconds(2);
    8.     myFunction();
    9.     yield return new WaitForSeconds(2);
    10.     myFunction();
    11.     yield return new WaitForSeconds(2);
    12.     myFunction();
    13.     yield return new WaitForSeconds(2);
    14.     /myFunction();
    15.     yield return new WaitForSeconds(2);
    16.     }
    17. }
     
  2. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    A for loop?

    Code (CSharp):
    1. IEnumerator myIEnumerator (){
    2.     for (int i = 0; i < 7; i++){
    3.         MyFunction();
    4.         yield return new WaitForSeconds(2);
    5.     }
    6. }
     
    ilyamep likes this.
  3. ilyamep

    ilyamep

    Joined:
    Feb 21, 2015
    Posts:
    12
    thanks very much, it works