Search Unity

Timer not working properly

Discussion in 'Scripting' started by Josenifftodd, Dec 20, 2014.

  1. Josenifftodd

    Josenifftodd

    Joined:
    Nov 29, 2013
    Posts:
    158
    I've done a timer script so when in battle once player has attacked the enemy it's suppose to count down the timer from 10 and when ) is hit, it lets my player attack again (ie, attack menu pops back up) very much like FF10 / FF10-X2

    Script attached below if anyone can figure out whats happening with it, the menu doesn't pop backup and the timer only goes to 9 and nothing else.

    Code (JavaScript):
    1. var timer : int = 10;
    Code (JavaScript):
    1. function Update () {
    2.         if(turn == 2 && enemyTurnActivated == false) {
    3.                 enemyTurnActivated = true;
    4.                 enemyTurn();
    5.                
    6.         }    timer -= Time.deltaTime;
    7.              
    8.        
    9.        
    10.        
    11. }
    12.  
    13.  
    14.  
    15. function enemyTurn () {   player.SendMessage("damagePlayer", Random.Range(1,10));
    16.         if (timer <= 0)
    17.         {          
    18.            
    19.            
    20.         turn = 1;
    21.         enemyTurnActivated = false;
    22.         }    
    23.      
    24.        
    25. }
     
  2. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
    This is probably a place you would want to call a coroutine to set the timer countdown every second and restore game play. You could look up WaitForSeconds and get some examples in the script reference. It would something like:
    while(timer > 0){
    yield WaitForSeconds(1);
    timer --
    }
    now do whatever
     
  3. Josenifftodd

    Josenifftodd

    Joined:
    Nov 29, 2013
    Posts:
    158
    somethng like this?

    Code (JavaScript):
    1. function enemyTurn () {   player.SendMessage("damagePlayer", Random.Range(1,10));
    2.         enemyTurnActivated = false;
    3.         yield WaitForSeconds (5);
    4.         turn = 1;
    5.      
    6.         }  
    7.    
    8.      
    9. }
     
  4. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
    Yeah, but if you use a loop, there's a countdown:
    Code (csharp):
    1.  
    2. function enemyTurn () {  player.SendMessage("damagePlayer", Random.Range(1,10));
    3.        enemyTurnActivated = false;
    4.        timer = 5;
    5.       while(timer>0){
    6.        yield WaitForSeconds (1);
    7.       timer--;
    8.         }
    9.         turn = 1;
    10.    
    11.      }
    12.    
    13.  
    14. }
     
    Josenifftodd likes this.