Cube placing on edges of cubes

Hey,

For a game i make i currently work on a building mechanic. i’ve got everything working just fine, just one little thing i cant figure out how to avoid.

The problem is, if you loot at the edge of a cube you placed you will place a cube that is floating in the air without beeing “connected” to another cube.

here an image for better understanding:

here is the code that is responsible for the cube placement:

if (Physics.Raycast(ray, out raycasthit, placeRange))
{
    if (raycasthit.transform.gameObject.tag == "Block" || raycasthit.transform.gameObject.tag == "Ground")
    {
        if (mode == 0)
        {
            Vector3 hitpoint = ray.GetPoint(raycasthit.distance - 0.2f);

            float ypos = ((hitpoint.y % 1 != 0) ? Mathf.FloorToInt(hitpoint.y) : hitpoint.y) + 0.5f;

            Vector3 placeAt = new Vector3(Mathf.RoundToInt(hitpoint.x), ypos, Mathf.RoundToInt(hitpoint.z));
            blockPlaceholder.transform.position = placeAt;
            blockPlaceholder.SetActive(true);
        }
    }
}

if (Input.GetMouseButtonDown(0))
{
    if(mode == 0)
    {
        GameObject newblock = Instantiate(block, blockPlaceholder.transform.position, Quaternion.Euler(Vector3.zero));
    }
}

Ignore the “mode”. This is a very cutdown version of the script since there is a lot of other stuff in there too.

i include the whole package too so you can test it out and change stuff easier.

would love to get some ideas on how to avoid this.

4330009–390463–blockplacingtest.unitypackage (360 KB)

Raycast down from the cube you’re about to place by 1 cube length distance and if there’s nothing there, don’t place the original cube?