Why does this script lag so much?

When I run this script the whole game lags a lot. I don’t have any graphics just a bunch of cubes, 3 to be exact. Here it is:

//this is the player we are targeting

var target : Transform;

//this is the speed that the enemy walks

var walkingSpeed : float;

	

	

	function Update () {

	

	//variables that are going to be used throughout the script

	var fwd : Vector3 = transform.TransformDirection(Vector3.forward);

	var collider : CharacterController = GetComponent(CharacterController);

	var ourX : int = transform.position.x;

	var ourZ : int = transform.position.z;

	var theirX : int = target.position.x;

	var theirZ : int = target.position.z;

	

		//this makes the enemy move towards the player

		

			//this makes the enemy move forward

			collider.SimpleMove(walkingSpeed * fwd * Time.deltaTime);

			

			//makes the enemy look at the player

			//first quadrant

			if(theirZ > ourZ && theirX < ourX) {

			

				print(1);

			}

			

			if(theirZ > ourZ && theirX > ourX) {

			

				print(2);

			}

			

			if(theirZ < ourZ && theirX < ourX) {

			

				print(3);

			}

			

			if(theirZ < ourZ && theirX > ourX) {

			

				print(4);

			

			}

				

			

		

			

			

			

			

}

@script RequireComponent(CharacterController)

Thanks! I don’t really want a fix to this script, I just want to know whats lagging so I don’t do this again.

It lags because you are printing to console every frame (times 3). Printing something to console takes a lot of time (relatively) and so when you do this every frame, things start to slow down.

Try to limit the amount you are printing.

I may not be correct in this, but try debugging and see what collider variable you actually get at line: `collider.SimpleMove(walkingSpeed * fwd * Time.deltaTime);` collider is a variable used within GameObject itself so it may be referencing that instead which may cause some weird things. Or does the program act the way you think it should?

EDIT: Also, in your Update() you are getting the CharacterController every update call which means every frame, so that eats a lot of time. Therefore, what you should do is remove that line from Update() and put it in a new function Start(); like so: (also rename collider to controller, or something)

private var controller : CharacterController;
function Start() {
    controller = GetComponent(CharacterController);
    if(!controller)
        Debug.Log("Cannot find player controller.");
}