- Home /
Question about coroutines
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
Do you know how long it takes for an AI to move before it's finished moving?
Answer by anniyan137 · Oct 30, 2013 at 01:38 PM
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.
http://www.youtube.com/watch?v=bM3CXzj5xM4
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.
Answer by Tomer-Barkan · Oct 30, 2013 at 02:08 PM
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;
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613120910im_/https://answers.unity.com/themes/thub/images/avi.jpg)