Move character's position to middle of object

Hello, here’s the code I have right now to make the character move to the center of an object. It only works if the object follows the global z axis though.

if(onObject)
{
    transform.position.z = Mathf.Lerp(transform.position.z, railPosition.z, Time.time * 3.0);
}

Here’s a diagram so you can see what I’m talking about:

if(onObject)
{
    transform.position = Vector3.Lerp(transform.position, railPosition, Time.time * 3.0);
}