enemy ai script that follows player within distance

I googled abit and found this script that makes the enemy chase my player, but the problem is, it chases the player from all over the map, not within a range, and im not familiar enough with unity to know where to put an if statement that makes it so the enemy only chases the player within range, if someone can help me out or give me a hint it would be much appreciated! here’s the code:

using UnityEngine;
using System.Collections;

public class MovingAI : MonoBehaviour {
	
	Transform target;
	Transform enemyTransform;
	public float speed = 3f;
	public float rotationSpeed=3f;
	public float detectionRange = 10;
	
	
	void Start () {
		//obtain the game object Transform
		enemyTransform = this.GetComponent<Transform>();
	}
	
	void Update(){
		
		target = GameObject.FindWithTag ("Player").transform;
		Vector3 targetHeading = target.position - transform.position;
		Vector3 targetDirection = targetHeading.normalized;
		
		//rotate to look at the player
		
		transform.rotation = Quaternion.LookRotation(targetDirection); // Converts target direction vector to Quaternion
		transform.eulerAngles = new Vector3(0, transform.eulerAngles.y, 0);
		
		//move towards the player
		enemyTransform.position += enemyTransform.forward * speed * Time.deltaTime;
		
	}
	
}

If your player has a collider and a rigidbody, you can use Physics.OverlapSphere() to look for the player in certain radius. Then you can check if the collider’s found contains the player’s collider. For example:

Collider[] foundColliders = Physics. OverlapSphere(enemyTransform.position, range_radius);

bool playerFound = false;

foreach(Collider coll in foundColliders)
{
    if(coll == playerCollider)
        playerFound = true;
}

if(playerFound)
{
    //your AI movement code
}

Place the code in your Update() function. For optimization, you can set the layermask parameter of Physics.OverlapSphere(). For more information you can visit the Script Reference.