Make a game object go to a specific point and come back to the previous starting position

Hello, guys. I would like some help on this.

I need help making a game object go to a specific point and come back to the previous starting position.

This is what I tried to do but didn’t quite get it.

Thank you so much for your time.

public class GrabObject : MonoBehaviour
{
[SerializeField] float rayDistance;
[SerializeField] LayerMask grabable;
[SerializeField] LayerMask ground;
[SerializeField] GameObject currentPrefab;
[SerializeField] float desiredDuration;
InputSystemManager inputSystemManager;
float startPos;
float elapsedTime;
// Start is called before the first frame update
void Start()
{
inputSystemManager = GameObject.FindAnyObjectByType();
startPos = transform.position.y;
}

// Update is called once per frame
void Update()
{
   

    
    if (inputSystemManager.ButtonPressedDown())
    {
        
        if (currentPrefab == null)
        {
            
            RaycastHit hitray;
            bool hit = Physics.Raycast(transform.position, Vector3.down, out hitray,rayDistance, grabable);
            Debug.Log(hit);
            if (hit)
            {
                //FindObjectOfType<AudioManager>().Play("Absorb");
                //Instantiate(spawnEffect, hit2D.point, Quaternion.identity);
                currentPrefab = GameObject.Find(hitray.collider.gameObject.name);
                //hasAnItem = true;


                StartCoroutine(LerpPosition(currentPrefab.transform.position));
                StartCoroutine(LerpPosition(new Vector3(transform.position.x, startPos, transform.position.z)));


            }
        }
        else
        {
            RaycastHit hitray;
            bool hit = Physics.Raycast(transform.position, Vector3.down, out hitray, rayDistance, ground);

            
            if (hit)
            {
                //FindObjectOfType<AudioManager>().Play("Spit");
                //Instantiate(spawnEffect, hit2D.point, Quaternion.identity);
                //hasAnItem = false;
                //Debug.Log("hitX");
                GameObject currentPrefabObj = Instantiate(currentPrefab, hitray.point, Quaternion.identity);
                currentPrefabObj.SetActive(true);
                currentPrefab = null;
            }
        }
    }
}

IEnumerator LerpPosition(Vector3 targetPos)
{
    float time = 0;
    
    while (time < desiredDuration)
    {
        transform.position = Vector3.Lerp(transform.position, targetPos, time / desiredDuration);
        time += Time.deltaTime;
        yield return null;
    }
    transform.position = targetPos;
}

The issue is that you are starting two conflicting coroutines one after the other. Coroutines are Async, meaning when you start them the rest of your code continues running too. So you are lerping to the prefab position, and then at the same time you instantly start lerping back towards your start position.

Instead you could do a few things, the first things that come to mind are:

  1. Create a check before running the second coroutine.
  2. Update your coroutine to become a more specific LerpPositionAndReturn() function that includes a return position as a second parameter, and maybe some extra values such as a wait time before returning.
  3. Take in a callback function that is executed at the end of your coroutine (more advanced, probably not necessary and there’s multiple ways to do this so I’m not entirely familiar with what’s best.)

That’s a lot of code… any reason you can’t just use a tweener and be done?!

Smoothing movement between any two particular values:

You have currentQuantity and desiredQuantity.

  • only set desiredQuantity
  • the code always moves currentQuantity towards desiredQuantity
  • read currentQuantity for the smoothed value

Works for floats, Vectors, Colors, Quaternions, anything continuous or lerp-able.

The code: SmoothMovement.cs · GitHub

Another approach would be to use a tweening package such as LeanTween, DOTween or iTween.

For your case you could Mathf.PingPong() a number from 0 to 1 and back to zero and use that as input to your Lerp… that would cause it to go from A to B and then back to A.