Search Unity

can't get a yield to work with an if

Discussion in 'Scripting' started by kobi666, Oct 13, 2014.

  1. kobi666

    kobi666

    Joined:
    Oct 13, 2014
    Posts:
    22
    i'm trying to get this to work,
    it's an example i copied from somewhere here, but once i put it in an 'if' it fails to start :


    #what i got, copied the text and it works fine :

    // Use this for initialization
    void Start() {
    Mylight = GetComponent<Light> ();
    print ("Starting " + Time.time);
    StartCoroutine (WaitS (bla));
    print ("Before WaitAndPrint Finishes " + Time.time);

    }

    IEnumerator WaitS(float waitTime) {
    yield return new WaitForSeconds(waitTime);
    print("WaitAndPrint " + Time.time);
    }

    # i want it to work with a key press so i put it inside an if :

    // Use this for initialization
    void Start() {
    Mylight = GetComponent<Light> ();
    if(Input.GetKey(KeyCode.L))
    {
    print ("Starting " + Time.time);
    StartCoroutine (WaitS (bla));
    print ("Before WaitAndPrint Finishes " + Time.time);
    }
    }

    IEnumerator WaitS(float waitTime) {
    yield return new WaitForSeconds(waitTime);
    print("WaitAndPrint " + Time.time);
    }


    #why is this not working?!?!
     
  2. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    9,435
  3. Pirs01

    Pirs01

    Joined:
    Sep 30, 2012
    Posts:
    389
  4. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,532
    First, lets wrap that in some code tags:

    Code (csharp):
    1.  
    2. // Use this for initialization
    3. void Start() {
    4.     Mylight = GetComponent<Light> ();
    5.     print ("Starting " + Time.time);
    6.     StartCoroutine (WaitS (bla));
    7.     print ("Before WaitAndPrint Finishes " + Time.time);
    8. }
    9.  
    10. IEnumerator WaitS(float waitTime) {
    11.     yield return new WaitForSeconds(waitTime);
    12.     print("WaitAndPrint " + Time.time);
    13. }
    14.  
    Code (csharp):
    1.  
    2. // Use this for initialization
    3. void Start() {
    4.     Mylight = GetComponent<Light> ();
    5.     if(Input.GetKey(KeyCode.L))
    6.     {
    7.         print ("Starting " + Time.time);
    8.         StartCoroutine (WaitS (bla));
    9.         print ("Before WaitAndPrint Finishes " + Time.time);
    10.     }
    11. }
    12.  
    13. IEnumerator WaitS(float waitTime) {
    14.     yield return new WaitForSeconds(waitTime);
    15.     print("WaitAndPrint " + Time.time);
    16. }
    17.  
    Next, your problem is you test for if the L key is down ONLY on Start. This is once, only once, and is at the beginning of the life of the script.

    You need to be testing for that key every frame and react accordingly.
     
  5. Deleted User

    Deleted User

    Guest

    Put your code in the update statement...
    And maybe keyup...