Need help with Enemy Script ( Enemy walks toward player only if in X range)

Hey guys,
Still new to this whole beast. Having a tough time figuring out how to edit my script so it only walks towards the player if the enemy is in X range.
Here is what we have so far:

var target : Transform;
var moveSpeed = 3;
var rotationSpeed = 3;
var myTransform : Transform;

function Awake(){
    myTransform = transform;
}

function Start(){
    target = GameObject.FindWithTag("Player").transform;
}

function Update(){
    transform.LookAt(Vector3(target.position.x, transform.position.y, target.position.z));

    myTransform.Translate(Vector3.forward * moveSpeed *Time.deltaTime);
}

Thanks all,
Help Appreciated
-Kav

1 Like

Thank you

two approaches come to mind

Set up a trigger collider which sets a boolean to true, check that boolean in the update function before the lookat/translate

Use raycasts towards the target to determine it’s distance, and set the same boolean as above. The (dis)advantage to this one would be that raycasts would be blocked by other colliders so it would be more “in range and in sight”.

both raycasting and colliders are covered in the physics learn section: http://unity3d.com/learn/tutorials/topics/physics

1 Like