Does Vector3.Lerp() for transforming position work outside of update?
asked May 07 '11 at 09:03 AM
It's a plain old function, so it 'works' anywhere - in that it will correctly calculate a value that is the linear interpolation between the start and end values. I use it, for example, in my AI code to compute how 'audible' a sound is based on how far away it is.
However, most of the time, when people are using Lerp(), they're trying to achieve smooth movement from point A to point B. To get smooth movement, you need to recompute the position very frequently - every frame, if possible.
Update() is called every frame, so you could call it there. You could also write a coroutine that does work every frame and calls it:
The advantage of doing it in a coroutine is that when the object isn't moving, the coroutine isn't running, which can save Unity a bit of time; by comparison, if you put the code in Update, Unity will always call Update, even if you end up not doing anything for the frame.
Also, with the coroutine approach, you can (if you wish) trade smoothness for framerate by yielding a WaitForSeconds() object instead of null. The longer you WaitForSeconds(), the jerkier the movement will be, but the less frequently Unity will have to do the computation.
answered May 07 '11 at 11:50 AM
It works wherever you want it to, it's a simple mathematical function, min + (max - min) * t
You can generally use it well in coroutines, where you have a fixed start and end, and increment the t value from 0 to 1
Quick example for a coroutine:
No, it is meant to be used within the Update() method.
answered May 07 '11 at 09:36 AM