- Home /
 
Adding a counter?
This script deducts health when my enemy collides with the player, Im wanting to make a timer or counter that decides when I take damage, In my last question I got told to do it like so
 var attackTimer : float = 0.0;
 var attackNow : float = 0.1; // 1 every 1/10 of a sec, or 10 every sec.
 
 function Update()
 {
     if ( attackTimer > attackNow )
     {
        // deduct health
        // reset Timer
        attackTimer = 0.0;
     }
     attackTimer += Time.deltaTime;
 }
 
               But im not sure how to implement it into this
 var fullHealth : int = 100;
 var curHealth : int = 100;
 
 function OnCollisionEnter(collision: Collision) {
 
 if(collision.gameObject.tag == "Enemy");
   curHealth -= 10;
 }
 
 function Update () {
 
 if(curHealth >= fullHealth){
     curHealth = fullHealth;
 }
 
   if(curHealth <= 0){
     curHealth = 0;
     Debug.Log("You are Dead");
 }
 }
 
 function OnGUI() {
     GUI.Label (Rect (25, 40, 100, 20), "Health = "+curHealth);
 }
 
               If anyone could help me I would be very grateful, thanks.
               Comment
              
 
               
               
               Best Answer 
              
 
              Answer by fafase · Sep 28, 2012 at 05:34 PM
 var fullHealth : int = 100;
 var curHealth : int = 100;
 function OnCollisionEnter(collision: Collision) {   
     if(collision.gameObject.tag == "Player")
           InvokeRepeating("ReduceHealth",0.01f,1.0f); 
 }
 function OnCollisionExit(collision: Collision) {   
     if(collision.gameObject.tag == "Player")
           CancelInvoke();
 }
 
 function OnGUI() {
     GUI.Label (Rect (25, 40, 100, 20), "Health = "+curHealth);
 }
 function ReduceHealth(){
     curHealth-=10;
 }
 
               The idea is that when you enter you start the invoke that is calling the function every 1 second. The first parameter cannot be 0 (nor 0.0) or you will lose twice on the first call (bug).
Your answer