AI Evasion help

Hi there, I’m having a little trouble with my avoidance script, I have a raysphere cast set up to detect if an enemy fighter is too close and then a random position is generated for it to fly towards and then after waiting 4 seconds it checks to see if the enemy is still too close otherwise it turns back and attacks, however they seem to be constantly flying around each other.

Debug.Log shows that they are doing the job right, but i’ve increased the random distance from 40 up to 500 and nothing changed. I have a feeling that i’ve missed something obvious or forgotten to add something important, but here’s the code if anyone has a clue

if (Physics.SphereCast (EvadePosition.position, 20, EvadePosition.forward, Hit, 20))
	{
		if(Hit.transform.tag == "Enemy")
		{
			IsAttacking = false;
			IsEvading = true;
			transform.Translate (0, 0, EvadeSpeed * Time.deltaTime);
			Evade();
		}
	}

function Evade ()
{
	var EvadePoint = Random.insideUnitSphere * 500;
	var rotation = transform.rotation;
	var position = transform.InverseTransformPoint(EvadePoint);
	var direction : float = position.x > 0 ? 1.0 : - 1.0;
	var angle = Vector3.Angle (Vector3.forward, position) * direction;;
	var targetDirection = (EvadePoint - transform.position).normalized;
	var lookRotation = Quaternion.LookRotation (targetDirection);
	transform.rotation = Quaternion.Slerp(rotation, lookRotation, TurnSpeed * Time.deltaTime);
	transform.Rotate (0,0,-angle * Roll);
	
	yield WaitForSeconds (4);
	
		IsAttacking = true;
		//Debug.Log("Resuming Attack - Blue Fighter");
		IsEvading = false;
		transform.Translate (0, 0, AttackSpeed * Time.deltaTime);
		Attack();
	
				
			
}

I think the problem is you are not checking if it is evading already before calling Evade() again.

if(Hit.transform.tag == "Enemy" && IsAttacking)

This should stop everything under that line from recalculating if you are already evading

if (Physics.SphereCast (EvadePosition.position, 20, EvadePosition.forward, Hit, 20))
	{
		if(Hit.transform.tag == "Enemy" && IsAttacking)
		{
			IsAttacking = false;
			IsEvading = true;
			transform.Translate (0, 0, EvadeSpeed * Time.deltaTime);
			Evade();
		}
	}

function Evade ()
{
	var EvadePoint = Random.insideUnitSphere * 500;
	var rotation = transform.rotation;
	var position = transform.InverseTransformPoint(EvadePoint);
	var direction : float = position.x > 0 ? 1.0 : - 1.0;
	var angle = Vector3.Angle (Vector3.forward, position) * direction;;
	var targetDirection = (EvadePoint - transform.position).normalized;
	var lookRotation = Quaternion.LookRotation (targetDirection);
	transform.rotation = Quaternion.Slerp(rotation, lookRotation, TurnSpeed * Time.deltaTime);
	transform.Rotate (0,0,-angle * Roll);
	
	yield WaitForSeconds (4);
	
		IsAttacking = true;
		//Debug.Log("Resuming Attack - Blue Fighter");
		IsEvading = false;
		transform.Translate (0, 0, AttackSpeed * Time.deltaTime);
		Attack();	
}