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

How to prevent this from spawning more than one?

It's a script I've been working on, but, whenever you touch it, it over spawns the thing in the lighting. Any help?

local part = script.Parent
local BeheadedRocketeer = game.Lighting.BeheadedRocketeer

part.Touched:connect(function()
local Enemy = BeheadedRocketeer:Clone()
	wait(1)
	Enemy.Parent = Workspace 
	wait(1)

end)

2 answers

✓ Accepted answer

For this, you need to use a technique called debounce. The reason it's spawning multiple times is because every instant the player touches the object, the event is fired again and again. With debounce, you tell the part that it can only be touched once every couple seconds. The basics of debounce work as follows:

1: Create a boolean variable and set it to true

2: On the Touched event, check if the boolean is set to true

3: If it's set to true, set it to false and run the code

4: Wait a few seconds, then set it to true again

Here's your code, with debounce:

local part = script.Parent
local BeheadedRocketeer = game.Lighting.BeheadedRocketeer

local debounce = true
part.Touched:connect(function()
if debounce == true then
debounce = false
local Enemy = BeheadedRocketeer:Clone()
    wait(1)
    Enemy.Parent = Workspace 
    wait(3) --waiting 3 seconds before setting debounce to true again
debounce = true
end
end)
local part = script.Parent
local BeheadedRocketeer = game.Lighting.BeheadedRocketeer
local running = false

part.Touched:connect(function()
if running == false then
running = true
local Enemy = BeheadedRocketeer:Clone()
    wait(1)
    Enemy.Parent = Workspace 
    wait(1)
running = false
end
end)

All you had to add was a value to see if the script was already running.

1 comment

0

Why the heck was this down voted? I got the script correct.

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