Range of Detection?

Hey guys, I’m very new to Unity so I don’t know what I would use to do this, but I would like to have an enemy rotate towards a player if it is within a certain radius. I’ve already managed to use some code but it doesn’t give me the range effect that I want. Any help? Here’s the code I currently have.

private GameObject target;
private Vector3 targetPoint;
private Quaternion targetRotation;

void Start () {
	rigidbody.velocity = transform.up * speed;
	target = GameObject.FindWithTag("Player");

void Update()
		targetPoint = new Vector3(target.transform.position.x, transform.position.y, target.transform.position.z) - transform.position;
		targetRotation = Quaternion.LookRotation (-targetPoint, Vector3.right);
		transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * 2.0f);

Any and all help is appreciated. I’m coding in C# but JavaScript answers are helpful as well.

If you just want a simple solution, put a Sphere Collider on your turret and enable the “IsTrigger” checkbox. Make sure your player has a collider as well. Then attach a rigidbody to either your turret or your player.

After you have attached those 3 components to your objects, you are ready to edit your turret script. Create a function on your script called OnTriggerEnter(). This function will be called by unity whenever your turret collider touches the player’s collider. Put your turret code there. See the example in the Unity documentation for reference:


Note: you have to attach a rigidbody to either your turret or your player or else Unity will not call OnTriggerEnter on the turret. If you don’t want to have the physics run on the rigidbody, then just enable the “Is Kinematic” checkbox on the rigidbody. This will allow OnTriggerEnter() to work, but the physics will not interfere with your gameplay.