Unity3d Update issue

I’ll make this short and clear. I got two scripts and I want to lower a number from one script to another.

Script #1 :

var healthBarDisplay : float = 1;

Script #2 :

var damage : float = 0.3f;
var Distance : float;
var attackRange : float = 1.0f;
var playerHealth : PlayerGUI;

function Awake()
{
	playerHealth = GameObject.FindWithTag("Player").GetComponent(PlayerGUI);
}

function Update()
{
    if(Distance < attackRange)
	{
		Attack();
	}
}

function Attack()
{
	animation.Play("Punching");
	playerHealth.healthBarDisplay -= damage;
}

This is not the whole script, only a part of it, the rest has nothing to do with what Im looking for.

Now, when the distance is lower then the attack range the healthBarDisplay from script 1 goes down too fast, because it’s being lowered in the update function , which updates every frame.

How do I make it so it lowers only once per second ? Adding time.deltatime doesn’t work the way I want it to.

Thank you, I hope I was clear enough.

Hey There,

I would suggest using a Timer. Invoking is a little messy and puts the power in Unitys hands.

private const float ATTACK_SPEED = 1.5f;
private float nextAttack = 0.0f; 

public void Update()
{
   if( Distance < attackRagne )
   {    
      if( nextAttack <= 0.0f )
      {
          Attack();
          nextAttack  = ATTACK_SPEED;
      }
      else
      {
        nextAttack -= Time.deltaTime;
      }
   }
   else
   {
      nextAttack = ATTACK_SPEED;
   }
}

Since BMayne decided to 1-up me, I decided to do it back :wink:
Here’s a pretty clean and efficient implementation.
Let me know if there’s something in the code below you don’t understand.

private bool cooldown = true;
private bool CanAttack { get { return cooldown && Distance < attackRange; } }

function Start() 
{
    InvokeRepeating( "ResetCooldown", 0, 1 );
}

function Update()
{
    if ( CanAttack )
        Attack();
}

function Attack()
{
    animation.Play("Punching");
    playerHealth.healthBarDisplay -= damage;
    cooldown = false;
}

void ResetCooldown() {
    cooldown = true;
}