Bring ray to gameObject.y position when mouse cursor is on a different point

Hello,

I have a gameObject instantiated on the scene and using

Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

in the Update function

when the mouse cursor is on the gameObject i get the objects coordinates that is fine and basic:

 if( Physics.Raycast( ray,out hit) )
	{

if(hit.collider.gameObject.tag==“sandcube”)

{
sandcubePos=hit.collider.gameObject.transform.position;

																						}


this is fine

now my mouse cursor is not on the gameObject and i press x button then i want the ray to be available from only the first collided gameObjects.y position which is:
sandcubePos.y so what i do is:

if(Input.GetKey(KeyCode.X))
{

ray=Camera.main.ScreenPointToRay(new Vector3(Input.mousePosition.x,sandcubePos.y,0));

but it doesnt work but supposed to!

if i write:
ray=Camera.main.ScreenPointToRay(new Vector3(Input.mousePosition.x,sandcubePos.y+300,0));

now the ray is quite close to the first collided gameObject when the mouse cursor is on a different point but it changes all the time depending on the collided gameObject!!

the code is attached to first person controller and the ray keeps changing

how to lock this mouse ray to only the collided game object with the mouse cursor collider(hit.point) no matter where my fpc object ,strange!!!

Referring to:

ray=Camera.main.ScreenPointToRay(new Vector3(Input.mousePosition.x,sandcubePos.y,0));

You cannot use this calculation because you are mixing screen coordinates and world coordinates. Input.mousePosition is in screen coordinates (pixels), and sandcubePos is in world coordinates. What you can do is save the Input.mousePosition.y from the previous raycast and use that for constructing this ray.