Hello All,
This is my first post here on the forums and I’m fairly new to Unity, so take it easy on me.
I’ve been writing a simple script to move an object from one way point to the next using the Lerp command. All worked fine with just one way point, but when I implemented a for loop to handle multiple way points, things got a little tricky.
Here is my script:
// Public Variables
public var Waypoints : GameObject[];
public var Speed : float;
// Private Variables
private var isFinished : boolean;
function Update()
{
if(!isFinished)
DoCo();
}
function LerpFunc(num : int) : IEnumerator
{
this.transform.position = Vector3.Lerp(this.transform.position, Waypoints[num].transform.position, Time.time * Speed);
}
function DoCo()
{
for(i=0; i <= Waypoints.Length - 1; i++)
{
Debug.Log("Lerping to Waypoint " + i.ToString());
yield LerpFunc(i);
}
isFinished = true;
}
Let me explain it. First, I add some GameObjects to the scene to serve as way points for the character and I assign them to the Waypoints array on the character. Second, the DoCo() function is called once and we loop through each way point and Lerp to it. I use the yield command to wait for the Lerp to complete before continuing with the loop.
However, when I test the scene, we are instantly at the end of the loop and the character is moved to a position close to the last way point, but not exactly on it.
I’m kind of at a loss here, and any help would be appreciated!