Help with TD placement

so, i am trying to make a TD game. My placement system mostly works, just one small problem. When placing, it keeps cloning the part (placeholder) multiple times. I know the issue, I just dont know how to solve it. Any Help?

while wait(0.05) do
	if placing == true then
		local unit = game.ReplicatedStorage.Towers.Part:Clone()
		unit.Parent = workspace
		if mouseRaycast() ~= nil then
			unit.Position = mouseRaycast().Position
		end
	end
end
1 Like

Disable placing variable after the player placed the tower,

while wait(0.05) do
	if placing == true then
		local unit = game.ReplicatedStorage.Towers.Part:Clone()
		unit.Parent = workspace
		if mouseRaycast() ~= nil then
			unit.Position = mouseRaycast().Position
		end
		placing = false
	end
end

yeah, but thing is, I want them to choose a position to place the tower, it’s a Gui button that when you click it it’s supposed to activate a “choose position” thing before you actually finalize your decision by double clicking.

Put the placing = false line into the if statement mouseRaycast() ~= nil then I guess?

while wait(0.05) do
	if placing == true then
		local unit = game.ReplicatedStorage.Towers.Part:Clone()
		unit.Parent = workspace
		if mouseRaycast() ~= nil then
			unit.Position = mouseRaycast().Position
			placing = false
		end
	end
end

nope, still does the same thing.

Is there a a script function in your code that does this?

ive tried, but im not really sure how to carry info from functions.

Well then, may I see the entire script? Can’t really understand what’s happening here.

here’s my script.
this is a local script just for now.

local placing = false

local function mouseRaycast()
	local mousePos = game:GetService("UserInputService"):GetMouseLocation()
	local mouseRay = workspace.CurrentCamera:ViewportPointToRay(mousePos.X, mousePos.Y)
	local raycastResult = workspace:Raycast(mouseRay.Origin, mouseRay.Direction * 1000)
	
	print(raycastResult)
	return raycastResult
end


	if placing == true then
		local unit = game.ReplicatedStorage.Towers.Part:Clone()
		unit.Parent = workspace
		unit.Position = mouseRaycast().Position
	end

script.Parent.MouseButton1Click:Connect(function()
	mouseRaycast()
	placing = true
end)



while wait(0.05) do
	if placing == true then
		local unit = game.ReplicatedStorage.Towers.Part:Clone()
		unit.Parent = workspace
		if mouseRaycast() ~= nil then
			unit.Position = mouseRaycast().Position
		end
	end
end

check if theres already a clone of the tower in workspace, if not then clone it

but wouldn’t that stop you from placing multiple of the same tower?