How to check layer between ray and hit collider in unity

First of all, please understand my poor English skills.

I’ve succeeded in detecting a specific layer using a layer mask.

However, if there is an object in the middle with the layers overlapping, it should stop, but we are detecting the water layer below.

Can you tell me how to cancel if there is a specific layer in the middle when you first detect a layer like this?

You could include both the Water and the Terrain in your layermask when performing the RayCast. Then you can check to see if the ray hit Terrain or Water first.
I’m most familiar with 2D, but I think this is how you would do it with 3D:

        //I'm just using arbitrary values for distance and origin
        float distance = 10;
        Vector3 origin = Vector3.zero;

        //I'm assuming that your terrain physics layers are named "Terrain" and "Water"
        LayerMask myMask = LayerMask.GetMask("Water", "Terrain");
        RaycastHit result = new RaycastHit();
        bool hit = Physics.Raycast(origin, Vector3.down, out result, distance, myMask);
        if(hit)
        {
            if(result.collider.gameObject.layer == LayerMask.NameToLayer("Terrain"))
            {
                //Terrain was hit first
            }
            else
            {
                //Water was hit first
            }
        }