So in my game. My AI is going thru all the units one by one in a list of gameobjects.
When it has a unit that is it going to control. It will first (in one scenario) try to first capture a building. If the unit is to far away. It will move towards the target.
Here is where the problem is. I want it to be able to try to capture again after it have moved. I dont want the game to continue the script while it is moving.
Is it possible with coroutine to move the target and then continue the script as normal (So just move the target and pause everything else)
If this dont work. I will have to just use the list in some other way
If using coroutines, you need to know the termination condition. It IS possible to use coroutines to move an object. This is illustrated in this video.
But I would instead go for a state machine where I would only make the object move when it is in the corresponding state and not do anything else.
You could set the Time.timeScale
to 0, and manually move the object based on realtime, not Time.deltaTime (which will be 0)
private bool movingWhilePaused = false;
private Vector3 moveWhilePausedTarget;
private float lastFrameRealTime;
public PauseAndMove(Vector3 target) {
movingWhilePaused = true;
moveWhilePausedTarget = target;
Time.timeScale = 0;
}
public Update() {
if (movingWhilePaused) {
Vector3 towardsTarget = moveWhilePausedTarget - transform.position;
Vector3 movement = towardsTarget.normalized * (Time.realtimeSinceStartup - lastFrameRealTime;
if (movement.sqrMagnitude >= towardsTarget.sqrMagnitude) {
movingWhilePaused = false;
Time.timeScale = 1;
Transform.Translate(towardsTarget);
} else {
Transform.Translate(movement );
}
}
lastFrameRealTime = Time.realtimeSinceStartup;
}