How do I make parts not be able to spawn inside each other?

Right now I have a part spawning system when a player clicks and goes to the mouse position, however the parts are anchored and they can spawn inside each other when clicked close by. I’ve tried for a while but I couldn’t get something that would work correctly. If I got anything on the post wrong then correct me since it is my first post.

Here is the code, it’s a local script parented into StarterCharacterScripts.

mouse = game.Players.LocalPlayer:GetMouse()

mouse.Button1Down:Connect(function()
	local part = Instance.new("Part")
	part.Anchored = true
	part.CanCollide = false
	part.TopSurface = 0
	part.BottomSurface = 0
	part.Position = mouse.Hit.Position
	part.Parent = game.Workspace
end)

If you test this you will notice that once you make a part then click again about a stud next to that part they will be inside each other, I want to know how I can make it so they cannot spawn inside each other.

1 Like

I think i found a solution


mouse = game.Players.LocalPlayer:GetMouse()

mouse.Button1Down:Connect(function()
	local part = Instance.new("Part")
	part.Anchored = false
	part.CanCollide = false
	part.TopSurface = 0
	part.BottomSurface = 0
	part.Position = mouse.Hit.Position
	part.Parent = game.Workspace.PARTS
	wait()
	part.Anchored = true

		
	for i,v in ipairs(workspace.PARTS:GetChildren()) do
		v.Touched:Connect(function(hit)
			print(v, "Hitted", hit)
			if hit.Parent == workspace.PARTS then
				hit:Destroy()
			end
		end)
	end
end)

Every time a new spawned part collides with nother pre-existent part it will be deleted

This script is slightly more efficient then the above one

mouse = game.Players.LocalPlayer:GetMouse()

mouse.Button1Down:Connect(function()
	local part = Instance.new("Part")
	part.Anchored = true
	part.CanCollide = false
	part.TopSurface = 0
	part.BottomSurface = 0
	part.Position = mouse.Hit.Position
	part.Parent = game.Workspace

    if #part:GetTouchingParts() > 0 then --May need to make this number a 1 if it doesn't work correctly
         part:Destroy()
    end
end)

thank you for the solutions @DenisxdX3, @PoppyandNeivaarecute however I still have a problem, what about walls? If I try the same thing on a wall it will do the same as the created parts before the solutions.

My script should still work, no matter what it is colliding with.

Edit - Never mind, your script actually does work with the created parts it just didn’t work at first because the part created with the script had cancollide off and it works with the walls as well, thank you.