"transform.Translate" with "yield WaitForSeconds"

Hi. I’m trying to set up a system to make an enemy patrol, but it isn’t working. The enemy just moves a small notch and then stops. I want The enemy to go forwards for a set amount of time and then go back. I don’t care about turning as the game is top down. What’s wrong with my script?

var movement : String;
var speed : float = 100;
var CenterObject : Transform;
var timeVar : float = 4;
function Update(){
	if(movement == "vertical"){
		EnemyMovement();
	}
	else if(movement == "rotate"){
		transform.RotateAround(CenterObject.position, Vector3.up, speed * Time.deltaTime);
	}
}

function EnemyMovement(){
	transform.Translate(Vector3.back * speed * Time.deltaTime);
	yield WaitForSeconds (timeVar);
	transform.Translate(Vector3.forward * speed * Time.deltaTime);
	yield WaitForSeconds (timeVar);
}

Thanks.

Translate is not a tween operation, it happens once every time you call it. I suggest looking into something like iTween for your tween needs.
http://itween.pixelplacement.com/index.php

Alternatively, you could do something like

float _timeToMove;
float _currentMovementTime;
float _movementSpeed;
string _movement;

void Update() {
	if (_movement == "vertical"){
		_currentMovementTime -= Time.deltaTime;
		if (_currentMovementTime <= 0){
			_currentMovementTime = _timeToMove;
			transform.Rotate(0,180,0);
		}
		transform.Translate(Vector3.forward * Time.deltaTime * _movementSpeed);
	}
}

You may want to look into how Coroutines actually work, I personally do not use UnityScript - but it looks to me like you are kind of half using a Coroutine but other parts of your logic (namely, calling it every update frame) are not taking that into consideration.

You don’t want to use Update for this anyway, just use coroutines. See MoveObject for simple movement coroutines.

–Eric

@Eric5h5 Thanks. I just got around to doing the rest of the script today. MoveObject is a tremendous help.