# Coroutines and Lerp - how to make them friends?

Hi there, so I’ve spent a bit of my time getting my head around coroutines which is a fantastic tool to have in your armoury. However, I’m confused by how to use a Vector3.Lerp within a coroutine - separately, I understand how they work, but I’m a little fuzzy as to how to make them work together. I’ve been pointed to a javascript piece of code here but this doesn’t make things much clearer for me. As always, any help is truly appreciated.

The two functions are completely orthogonal- there’s no reason whatsoever why they can’t work together!

In fact, they are particularly useful in conjunction. Here’s a simple bit of code for making an object move to a new position over a period of n seconds.

``````function MoveToPosition(newPosition : Vector3, time : float)
{
var elapsedTime : float = 0;
var startingPos : Vector3 = transform.position;
while (elapsedTime < time)
{
transform.position = Vector3.Lerp(startingPos, newPosition, (elapsedTime / time));
elapsedTime += Time.deltaTime;
yield;
}
}
``````

Simply call that function with StartCoroutine, and it’ll all work!

``````StartCoroutine(MoveToPosition(new Vector3(0, 10, 0), 5));
``````

And for C#

``````    private IEnumerator FadeOut(float alphaStart, float alphaFinish, float time)
{
if (bgTexture == null)
yield return null;

float elapsedTime = 0;
bgTexture.alpha = alphaStart;

while (elapsedTime < time)
{
bgTexture.alpha = Mathf.Lerp(bgTexture.alpha, alphaFinish, (elapsedTime / time));
elapsedTime += Time.deltaTime;
yield return new WaitForEndOfFrame();
}
}
``````