Bug with my enemyAI

I got a simple basic enemyAI script of the unityanswers, and i need some help with it it is for a First Person RPG Adventure game i am working on.
When the enemy chases you lose health, (heaps of health), When you should only lose one health, when the enemy is actually near you and attacking you. Here is the enemyAI script

var Player : Transform;
var MoveSpeed = 4;
var MaxDist = 10;
var MinDist = 5;

function Start ()


function Update ()

if(Vector3.Distance(transform.position,Player.position) >= MinDist){

     transform.position += transform.forward*MoveSpeed*Time.deltaTime;

     if(Vector3.Distance(transform.position,Player.position) <= MaxDist)



The way your code is now, every frame that your enemy is close enough to your player, it is taking 1 health from your player. Games run at many frames per second, which is why your player’s health is going down very quickly. You need to set some kind of timer variable to put time between attacks so that health doesn’t drain all at once like that.

Define a float variable called “attackTimer” and set it to 0.0f, and change your code to this:

if(Vector3.Distance(transform.position,Player.position) <= MaxDist) {

if(attackTimer <= 0.0f) {



attackTimer = 1.0f;

} else {

attackTimer -= 1.0f * Time.deltatime;



That should do the trick. With this code, your enemy will only be able to attack once per second. You can change how quickly your enemy can attack by editing the 1.0f in the else statement. A bigger value will let him attack faster.

So the problem is that Update() runs many times per second, and for each of those frames where the distance check between enemy and player is less than MaxDist the player loses -1, and that adds up very fast (think “60 frames per second”).

You should consider adding an attack delay, there are thousands of attackdelay timer examples already on UA/Google