Check lenght from player?

Basically, I have this AI script that tracks the player, and moves to it - I was wondering if there is a way to make it only follow the player if the player is less than a length from the enemy? Thanks in advance.

This is my script:

	public Transform target;
	public int moveSpeed;
	public int rotationSpeed;
	public int maxdistance;
	private Transform myTransform; 
	
	void Awake()
	{
		myTransform = transform;
	}
	
	
	void Start ()
	{
		
		maxdistance = 0;
	}
	
	
	void Update ()
	{
		
		
		if (Vector3.Distance(target.position, myTransform.position) > maxdistance)
		{
			// Get a direction vector from us to the target
			Vector3 dir = target.position - myTransform.position;
			
			// Normalize it so that it's a unit direction vector
			dir.Normalize();
			
			// Move ourselves in that direction
			myTransform.position += dir * moveSpeed * Time.deltaTime;
		}
	}
}

Hi, you can try this:

Transform player;
Transform _transform;

public float minDistToFollow;
public float maxDistToFollow;

void Start()
{
	player = // Get your player
	_transform = transform // Cache my transform to avoid GetComponent<T>
}

void FollowPlayer()
{
    // Start follow Logic
}

void StopFollowPlayer()
{
	// Stop follow logic
}

bool ShouldFollowPlayer()
{
	if(Vector3.Distance(player.position, _transform.position) < minDistToFollow)
	{
		return true;
	}
	else
	{
		return false;
	}
}

void Update()
{
	if(ShouldFollowPlayer())
	{
		FollowPlayer()
	}
	
	if (Vector3.Distance(player.position, _transform.position) > maxDistToFollow)
	{
		StopFollowPlayer();
	}
}

I’m actually a bit confused because your code shows that you already know the answer to your own question.

On line 24, change it to less than the “maxdistance”:

 if (Vector3.Distance(target.position, myTransform.position) < maxdistance)

So now the AI will only turn and follow the player when the distance between the player and the AI is less than “maxdistance”

Of course, in your void Start(), you have to change the “maxdistance” to something greater than 0.