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. Dismiss Notice

Simple timer to minus a Var in Javascript

Discussion in 'Scripting' started by byro210, Jun 12, 2014.

  1. byro210

    byro210

    Joined:
    Feb 18, 2014
    Posts:
    121
    I tried using a tutorial but it just doesn't seem to work for me or what im looking for, so in JavaScript could I make a simple timer that every 10 seconds reduces the var MonsterHealth: int; by 5?
     
  2. diegzumillo

    diegzumillo

    Joined:
    Jul 26, 2010
    Posts:
    418
    You can do this in a few ways. The first thing that crosses my mind is invokeRepeating() (read here how this function works) but it doesn't give you a lot of power over the call. Once it starts calling the function you specify (a function that reduces the health, in your case) you can't change the amount of time and you can't stop (you can, but then you cancel every invoke repeating running). So I'll describe how to do this by hand.

    Code (JavaScript):
    1. var timer : float = 0;
    2. var rate : float = 10;
    3. var reduceHealth : boolean = true;
    4. function Update(){
    5.     if( reduceHealth && timer >= rate ){
    6.         monsterHealth -= 5;
    7.         timer = 0;
    8.     }
    9.     timer += Time.deltaTime;
    10. }
    11.  
    You could, of course, set timer to 10, reduce deltatime from it and ask if it's equal or smaller than 0. It's all the same.

    Hope this helps.
     
  3. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,398
    No, you just CancelInvoke("MyFunction") and it only cancels that particular one.

    --Eric
     
  4. byro210

    byro210

    Joined:
    Feb 18, 2014
    Posts:
    121
    Thanks that worked awesomely :)
     
  5. diegzumillo

    diegzumillo

    Joined:
    Jul 26, 2010
    Posts:
    418
    Thanks for the info! that makes invokerepeating much more useful, actually.