Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by
14dark14 167
4 years ago
Edited 4 years ago

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.

0
Is it actually a button that you click or is it something you walk on like a spawner pad? eyeball001 7 — 4y
0
GUI BUTTON 14dark14 167 — 4y
0
TEXTBUTTON 14dark14 167 — 4y
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. xInfinityBear 1777 — 4y

2 answers

Log in to vote
1
Answered by
sheepposu 561 Moderation Voter
4 years ago

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

Ad
Log in to vote
1
Answered by 4 years ago

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)

Answer this question