- Home /
OnGui.Button Lerp Object
Trying to find the best way to move an Object on a GUI.Button click.
OnGUI creates the button, and sets a variable.
private void OnGUI()
{
if (GUI.Button(new Rect(450, 450, 64, 64), "Click to Move"))
{
_startMoving = true;
}
}
Then Update calls MoveObject()
private void Update()
{
MoveObject();
}
private void MoveObject()
{
if (!_startMoving) return;
if (_moving) return;
_moving = true;
var pointA = _sphere.transform.position;
var t = 0f;
while (t < 1)
{
t += Time.deltaTime/duration;
_sphere.transform.position = Vector3.Lerp(pointA, new Vector3(3f, -8f, 3f), t);
}
_moving = false;
}
This moves the object, but just re-positions it across in one frame.
What is causing the code to not Lerp it smoothly
Is the correct method of Making objects move OnGui.Button click?
Kind regards
Answer by Berenger · Jan 22, 2013 at 09:55 AM
MoveObject is executed only once, and the entire movement is done in one frame, so your object is teleported.
Instead, check out coroutines : http://docs.unity3d.com/Documentation/ScriptReference/Coroutine.html. They can pause their execution for some time and let the code continue. In your case, you'll have to wait for one frame at each iteration, which is done by "yield return null;".