Placement System: How do I make it so a object can't be placed on another object.

I have created a very simple way to place an object in unity but currently, it can place objects inside each other. How do I stop this from happening?

Heres my placement code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Builder : MonoBehaviour
{
public Transform _object;

public LayerMask hitLayers;

void Update()
{
	Vector3 mouse = Input.mousePosition;
	Ray castPoint = Camera.main.ScreenPointToRay(mouse);
	RaycastHit hit;
	if (Physics.Raycast(castPoint, out hit, Mathf.Infinity, hitLayers))
	{
		_object.transform.position = hit.point;
	}

	if (Input.GetMouseButtonDown(0))
	{
		Instantiate(_object, hit.point, Quaternion.identity);
	}
}

}

Hi @Yoin,

Ok so it seems there are two different issues here.

  1. Initially placing the block inside another object
  2. Objects can be overlayed.

A solution for Problem 1:
You can simply move the object according to its scale and normal:

_object.transform.position = hit.point + _object.transform.scale.y/2 * hit.normal;

A solution for Problem 2:

In the past a made a minecraft style spaceship building game - infact I am still busy with it. I had the same problem you had and the way I got around it was using a “Aim Block”. This is how it works:

  1. Create a duplicate of the object you are placing
  2. Instantiate the object and let it follow around your mouse cursor.
  3. Slightly decrease the collider size.
  4. If it is not collidign with something then allow the real block to be placed at the same location

Hope this helps!