Enemy Attacking Even When Not In Range

So I have this small enemy AI (look at the player and follow him if in range) but the only problem is the “if in range” part seems to be irrelevant!

Here’s my script:

    #pragma strict

var Player : Transform;
var MoveSpeed = 5;
var MaxDist = 7;
var MinDist = 6;
var AttackDistance = 5;
var PlayerHealth = 100;
 
function Start () 
{
 
}
 
function Update () 
{
    transform.LookAt(Player);
     
     
    transform.position += transform.forward*MoveSpeed*Time.deltaTime;
 
    if(Vector3.Distance(transform.position,Player.position) <= AttackDistance);
    {
        PlayerHealth = PlayerHealth - 0.000001;
        print(PlayerHealth);
    }
    if(PlayerHealth <= 0) {
        Application.LoadLevel(1);

   }
}

if(Vector3.Distance(transform.position,Player.position) <= AttackDistance) >;< THIS!!!
you ended the statement with that semicolon :), remove it

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

I would imagine this is because your movement code is just inside your update, meaning the movement code is not bound to any “too close / too far” logic at all. Try something like this.

function Update () 
{
	// Rotate to face player.
	transform.LookAt(Player);


	if(Vector3.Distance(transform.position,Player.position) <= AttackDistance);
	{
		// Player within range. damage player.
		PlayerHealth = PlayerHealth - 0.000001;
		print(PlayerHealth);
		
		// Only need to check player health here as this is where it is decreased.
		if(PlayerHealth <= 0) 
		{
			Application.LoadLevel(1);
		}
	}
	else
	{
		// Too far away, move towards player.      
		transform.position += transform.forward*MoveSpeed*Time.deltaTime;
	}
}

I’ve added an else to your distance check so that if the player is not within range that will then trigger the movement logic. Additionally I moved the health check to where the health is decreased. It’s a minor optimization so feel free to ignore that part, the important part is the else, and the movement of the transform.position change into it.