- Home /
Move along several Vector3 in a coroutine
Hello,
I have an hexagonal board, where I can click and draw a path with the mouse to move my character along this path: The Vector3 position of each cell is store in a Vector3 array and my problem is to be able to move smoothly my character along each cell. For that I try with a coroutine:
void Update() {
if (...) {
StartCoroutine(Move_Routine(this.transform, listPathTransform));
}
}
private IEnumerator Move_Routine(Transform transform, List<Vector3> vectors) {
for(int i = 0; i < vectors.Count - 1; i++) {
float t = 0f;
Vector3 a = vectors[i];
Vector3 b = vectors[i+1];
while (t < 1f) {
t += Time.deltaTime;
transform.position = Vector3.Lerp(a, b, Mathf.SmoothStep(0, 1, t));
yield return null;
}
}
}
I am not very confortable with coroutine yet, and I don't know if it is a good idea to use it for this problem. The result of my code is that the character will move smoothly from its position to the first selected cell but will not continue (like the for loop never increase i). Do you have any idea why is it like this or any suggestion about how to solve this problem (coroutine or not)? Thank you!
Answer by Bunny83 · May 25, 2019 at 05:48 PM
I don't see an issue with your code. The only thing that could be problematic is that you use a List which could be changed outisde the coroutine while the coroutine is running. Are you sure that you don't clear the list after you started the coroutine? If you want to clear it you have to provide a copy of the list.
Personally I would do the loop like this:
if (vectors.Count == 0)
yield break;
Vector3 start = vectors[0];
for(int i = 1; i < vectors.Count; i++)
{
Vector3 end = vectors[i];
float t = 0f;
while (t < 1f)
{
t += Time.deltaTime;
transform.position = Vector3.Lerp(start, end, Mathf.SmoothStep(0, 1, t));
yield return null;
}
start = end;
}
Though yours should work equally well. If you're not sure if the list might be changed during the coroutine you can create an array at the beginning
private IEnumerator Move_Routine(Transform transform, List<Vector3> vectors)
{
Vector3 points = vectors.ToArray();
for(int i = 1; i < points.Length; i++)
{
// [ ... ]
This ensures no trouble with any changes to the list.
Your answer

Follow this Question
Related Questions
Moving the player toward a direction 1 Answer
MoveTowards inside Coroutine 2 Answers
Calculating the Exact Center of Multiple Objects 2 Answers
Object keeps moving up even when StopCoroutine is called 2 Answers