Enemy follows you only when it sees you

Hello,

I have a script which makes the enemy follow you if its raycast hits you, and if it is inside a certain zone. There is a cube named “BoundaryCube” that is on the ceiling of the scene.
var thePlayer : Transform;
var centrePoint : Transform;

function Update(){
	var hit : RaycastHit;
   	Debug.DrawRay(transform.position, transform.up, Color.red);
  	if(Physics.Raycast(transform.position, transform.up, hit)){
        	if(hit.collider.gameObject.name == "BoundaryCube"){
        			var targetPosition = thePlayer.position;
				targetPosition.y = transform.position.y;
				transform.LookAt(targetPosition);
 				transform.position = Vector3.MoveTowards(transform.position, thePlayer.transform.position, .05);
		}
	}
}

So when you open a door and go through it, the enemy is supposed to turn around and go back to a game object named CentrePoint because only the main area is covered by the above BoundaryCube.

The problem is not knowing how to make the enemy only look for you IF it is not moving back to the centre.

Does anyone know any code I can use?

Thanks

As Yokimato mentioned, this is a simple solution of tracking the state of the enemy. Here’s three options of doing so, as this issue can start simple, but quickly grow to an unmanageable mess later.

Simple solution: Flip a bool

isReturningToOrigin = true;

if (!isReturningToOrigin)
    LookForPlayer();

Forward-thinking solution: State enemy

Your enemy will probably have more mutually-exclusive states than 1, so good idea to make a state enum and plan for future states.

enemy.state = EnemyState.RETURNING_TO_ORIGIN;

switch (enemy.state)
    case EnemyState.LOOKING_FOR_PLAYER:
        LookForPlayer();
        break;

Advanced solution: State machine

Maybe keys for states are still an enum, but basically each state is a class with the state-specific code inside it.

enemy.ChangeState( EnemyState.RETURNING_TO_ORIGIN );

And then all your enemy does is update his current state. All the specific code is in that particular state’s class.

enemy.state.Update();

Hope that gives you some options and ideas of where you can take this in the future.