I’m using a Coroutine to launch a hook to an enemy and switch places with him on a grid.
Everything is working as expected except that I have unwanted pauses between each while inside my coroutine and also at the end of the function. Here’s my code:
IEnumerator HookSmooth(GridPoint2 target, float lineDrawSpeed)
{
GameObject enemy = goulsGrid[target].transform.GetChild(0).gameObject;
line.SetPosition(0, transform.position);
float counter = new float();
float dist = Vector3.Distance(transform.position, goulsGrid[target].transform.position);
Vector3 pointA = transform.position;
Vector3 pointB = goulsGrid[target].transform.position;
while (counter < dist)
{
counter += 0.1f / lineDrawSpeed;
float x = Mathf.Lerp(0, dist, counter);
Vector3 pointAlongLine = x * Vector3.Normalize(pointB - pointA) + pointA;
line.SetPosition(1, pointAlongLine);
yield return 0;
}
counter = 0;
while (counter < dist)
{
counter += 0.1f / lineDrawSpeed;
float x = Mathf.Lerp(0, dist, counter);
Vector3 pointAlongLine = x * Vector3.Normalize(pointB - pointA) + pointA;
line.SetPosition(0, pointAlongLine);
//Move Player
transform.position = pointAlongLine;
//Move Enemy
enemy.transform.position = Vector3.Lerp(pointB, pointA, counter);
yield return null;
}
}
The question is why I have a pause between the two while loops and also a pause at the end of my coroutine? I’m guessing that the yield return null lines are somehow producing a pause?
I don't think the problem is directly related to the coroutine. The Lerp calls expect an "t" input in the range from 0 to 1. So if "dist" is >1, you won't see any movement from the moment "counter" reaches 1.0.
– doublemax@doublemax Thank you for the answer. But in that case, shouldn't the while loop stop (and with it, the coroutine as well) when "dist" is > 1 ? Is there a way to prevent very small difference numbers on "counter"?
– Rodlaizps: Never use
– Bunny83yield return 0;. It creates garbage on the heap because "0" is a value type and need to be [boxed][1]. If you want to wait one frame, just useyield return null;. That doesn't create any garbage. [1]: http://stackoverflow.com/questions/2111857/why-do-we-need-boxing-and-unboxing-in-c