Search Unity

How can I change till Invoke() actives?

Discussion in 'Scripting' started by Stef_Morojna, May 26, 2015.

  1. Stef_Morojna

    Stef_Morojna

    Joined:
    Apr 15, 2015
    Posts:
    289
    I want to change the time when invoke activates.

    for example.

    Code (CSharp):
    1. void Start(){
    2. Invoke( "Example", 20);
    3. }
    4.  
    5. //I would like that when for example, the player presses a key
    6. //  1 extra second will be added to the countdown.
    7.  
    8. void Example() {
    9.  
    10. }
     
    Last edited: May 26, 2015
  2. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,537
    I wouldn't use Invoke for this. I'd use a coroutine that ticked a timer for some duration, but if a key was pressed it adds 1 second. Something like this:

    Code (csharp):
    1.  
    2. void Start()
    3. {
    4.     this.StartCoroutine(this.WaitForDurationWithKeyPress(20f));
    5. }
    6.  
    7. IEnumerator WaitForDurationWithKeyPress(float dur)
    8. {
    9.     while(dur > 0f)
    10.     {
    11.         yield return null;
    12.         if(Input.GetKeyDown(KeyCode.Return)) dur += 1f;
    13.         dur -= Time.deltaTime;
    14.     }
    15.  
    16.     //do what is necessary
    17. }
    18.  
     
    Kiwasi likes this.
  3. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Yeah, the answer is a coroutine.