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.

  1. What is causing the code to not Lerp it smoothly
  2. Is the correct method of Making objects move OnGui.Button click?

Kind regards

MoveObject is executed only once, and the entire movement is done in one frame, so your object is teleported.

Instead, check out coroutines : Unity - Scripting API: Coroutine. 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;”.