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

How can I run a touched function only once?

I'm making an obby in studio where the blocks fall from the sky and you jump on them. But when I tested it like 7 or 8 blocks dropped but I only wanted 1 block. How can I fix this without writing too much new code? I'm new to scripting so I'm not that good.Here is the script:

function CUBE1()
	local cube100 = Instance.new("Part")
	cube100.Position = Vector3.new(-218.82, 50, -243.53)
	cube100.Material = "SmoothPlastic"
	cube100.Size = Vector3.new(9,1,8.38)
	cube100.BrickColor = BrickColor.new("Really blue")
	cube100.Parent = game.Workspace.Cubes
end

game.Workspace.ObbyStarter.Touched:Connect(CUBE1)

2 answers

✓ Accepted answer

Try setting the listener to a variable and disconnect it inside the function.

function CUBE1()
    local cube100 = Instance.new("Part")
    cube100.Position = Vector3.new(-218.82, 50, -243.53)
    cube100.Material = "SmoothPlastic"
    cube100.Size = Vector3.new(9,1,8.38)
    cube100.BrickColor = BrickColor.new("Really blue")
    cube100.Parent = game.Workspace.Cubes

    connection:Disconnect()
end

connection = game.Workspace.ObbyStarter.Touched:Connect(CUBE1)

easy

local debounce = false

function CUBE1()
    if debounce == false then
		debounce = true
		local cube100 = Instance.new("Part")
 		cube100.Position = Vector3.new(-218.82, 50, -243.53)
 		cube100.Material = "SmoothPlastic"
		cube100.Size = Vector3.new(9,1,8.38)
		cube100.BrickColor = BrickColor.new("Really blue")
		cube100.Parent = game.Workspace.Cubes
		wait(5) --how much time for it to work again
		debounce = false
	end
end

game.Workspace.ObbyStarter.Touched:Connect(CUBE1)

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