Help with Basic AI

Hi! I am starting to write AI code and I’m having some issues with a very simple AI.

The issue:

I want the enemy to stop as soon as he enters the maxDistance variable, so he cannot keep going forward. I think my code is right, but it doesn’t work and I can’t find the
problem. Thank you! :smiley:

The code:

using UnityEngine;
using System.Collections;

public class BasicAI : MonoBehaviour {

private GameObject player;
public float distance;
private CharacterController thischar;
public float speed = 5.0f;
public Vector3 movementh = Vector3.zero;
public float chaseRange = 1.0f;
public float attackRange = 1.5f;
public float gravity = 20.0f;
public float lookatdistance = 20.0f;
public float dumping = 8.0f;
public float maxDistance = 0.4f;

// Use this for initialization
void Start () {

	player = GameObject.FindWithTag ("Player");
	thischar = GetComponent <CharacterController>();
}

// Update is called once per frame
void Update () {
	distance = Vector3.Distance (player.transform.position, transform.position);
	movementh.y -= gravity * Time.deltaTime;
	thischar.Move (movementh * Time.deltaTime);

	if (distance <= chaseRange)
	{
		if (distance >= maxDistance)
		{
			movementh = transform.forward * speed;
			print ("la distancia es mas grande que la maxima");
		}
		else
		{
			movementh = Vector3.zero;
		}
	

	}
	else
	{

		if (distance <= lookatdistance)
		{
			LookAt ();

		}

	}


			

}

void LookAt ()
{

		Quaternion rotation = Quaternion.LookRotation (player.transform.position - transform.position);
		transform.rotation = Quaternion.Slerp (transform.rotation, rotation, Time.deltaTime * dumping);
}

}

I did something which might help, feel free to add to it, its bareeeebones. You’ll need to loop when I disable the script so that it isn’t permanently disabled, but otherwise it could be helpful.

using UnityEngine;
using System.Collections;

public class EnemyAI : MonoBehaviour {
	public GameObject target; 
	public bool foundPlayer; 
	public Vector3 myPosition;
	public float speed = 1.0f; 

	public EnemyAI myAI; 


	void Start () {
	// Locate the Player object. 
		if(GameObject.FindWithTag("Player"))
		{
			myAI = GetComponent<EnemyAI>(); 
			foundPlayer = true;
		}

	}

	void Attack() 
	{
		myPosition = transform.position;
		transform.position = Vector3.Slerp(myPosition, target.transform.position, speed * Time.deltaTime);


	}

	void Update () {
		if(foundPlayer == true) 
		{
			Attack(); 

			if(Vector3.Distance(myPosition, target.transform.position)<2.0f)
			{
				myAI.enabled = false;
			} else
			{
				myAI.enabled = true;
			}
		}


	}
}