Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I prevent clone() function running more than once? Advance?

So you can spawn in a car as a player using a GUI button, but I've accidentally spawned 2 cars clicking the button.

Script in ServerScriptService

game.ReplicatedStorage.DuneBuggy.OnServerEvent:Connect(function()
	    local endPosition = Vector3.new(23.473, 25.199, -151.075)
	    local model =  game.ServerStorage.DuneBuggy:Clone()
	    local cframe = model.PrimaryPart.CFrame
	    model.Parent = game.Workspace

            model:SetPrimaryPartCFrame(cframe * CFrame.Angles(0,math.rad(180),0))

            model:MoveTo(endPosition)
end)

Basically the RemoteEvent got fired twice and caused 2 cars to spawn. Any way to prevent this? I added a debounce script to the GUI button but still managed to spawn the car twice.

4 comments

0

Is it actually a button that you click or is it something you walk on like a spawner pad?

0

GUI BUTTON

0

TEXTBUTTON

0

Can you include the Local Script that's firing the Event? As the problem seems to be in there as it's firing the event repeatedly.

2 answers

✓ Accepted answer

I would suggest using a debounce, it's a very common thing to use with events and such. Here's a simple example.

local debounce = false

script.Parent.Touched:Connect(function(hit)
	if not debounce then
		debounce = true
		print(hit)
		wait(1) --Wait one second before setting debounce back to false and allowing the script to run again. This could also be used to make sure that a button only works once every second or something like that.
		debounce = false
	end
end)

Hope this helps

You could also add a debounce to the server script too

local debounce = false
game.ReplicatedStorage.DuneBuggy.OnServerEvent:Connect(function()
	if debounce == false then
		debounce = true
		local endPosition = Vector3.new(23.473, 25.199, -151.075)
		local model =  game.ServerStorage.DuneBuggy:Clone()
		local cframe = model.PrimaryPart.CFrame
		model.Parent = game.Workspace
		model:SetPrimaryPartCFrame(cframe * CFrame.Angles(0,math.rad(180),0))
		model:MoveTo(endPosition)
		wait(5)
		debounce = false
	end
end)

This discussion is preserved as it was. New answers, comments, and votes are closed.