After using transform.position, gameobject resets z-axis position

Hi everyone.

I’m trying to do something “simple”: to make the gameobject move towards the player’s touch (on the X-Y plane), while moving the gameobject along the Z-axis at a constant speed. The first part, I’ve managed. The second, not so much.

using UnityEngine;

public class Player : MonoBehaviour
{
	//flag to check if the user has tapped
	//Set to true on tap. Reset to false on reaching destination
	private bool shouldmove = true;
	//destination point
	private Vector3 endPoint;
	private float zPosition;

	Ray ray;
	RaycastHit raycast;

    public float duration = 50f;
	public float FwSpeed = 1f;

    private Rigidbody _rigidbody;

	void Start()
	{
		zPosition = _rigidbody.position.z;
	}
	
    void Awake()
    {
        _rigidbody = GetComponent<Rigidbody>();
    }

    void Update()
    {
		if(Input.touchCount > 0 && (Input.GetTouch(0).phase == TouchPhase.Began || Input.GetTouch(0).phase == TouchPhase.Moved))
		{
			ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);

			if(Physics.Raycast(ray,out raycast))
			{
				endPoint = raycast.point;
				endPoint.z = zPosition;
				Debug.Log(endPoint);
				shouldmove = true;
			}
		}


		if(shouldmove && !Mathf.Approximately(_rigidbody.position.magnitude, endPoint.magnitude))
		{
			_rigidbody.transform.position = Vector2.Lerp
				(
				_rigidbody.position,
				endPoint ,
				1/(duration*(Vector2.Distance(_rigidbody.position, endPoint)))
				);
		}

		else if(shouldmove && Mathf.Approximately(_rigidbody.position.magnitude, endPoint.magnitude))
		{
			shouldmove = false;
			Debug.Log("I am here");
		}
		_rigidbody.velocity = new Vector3(_rigidbody.velocity.x, _rigidbody.velocity.y, FwSpeed);
		zPosition = _rigidbody.position.z;
    }
}

For some reason, it resets the gameobject.position.z to 0 after the transform.position. Any clue to as to why and how to fix it?

Figured it out, re-wrote the code so it doesn’t use transform.position, shifted all movement to rigidbody.velocity.