How to make touched event trigger only once

maybe someone has asked this before and i just havent found the post but basically

i have a part that plays a sound when touched, but it keeps continously playing it because it is constantly being touched. solution would be a simple debounce, what i did was set the debounce to like 900 when touched and set it back to 0 when the touch ended.

now the issue with this is that this is done on the server, so lets say player1 walks inside the part and doesnt leave. so now that the touch didnt end the debounce is still 900 and now if player2 tries to walk inside while player1 is still in there it won’t play

any solutions?

1 Like

If you want it to only trigger once and never again, use :Once

part.Touched:Once(function()
    print("this will only be printed once")
end)

Here’s the API Doc reference: RBXScriptSignal | Documentation - Roblox Creator Hub
P.S., there’s no need to disconnect this since it auto-disconnects after its initial usage, quite obviously.

6 Likes

maybe try changing run context to client

Try making the debounce a table instead of a boolean.

local debounce = {}
part.Touched:Connect(function(hitPart)
	local character = hitPart:FindFirstAncestorOfClass("Model")
	if character then
		if character:FindFirstChild("Humanoid") then
			if not debounce[character.Name] then
				debounce[character.Name] = true
				-- play sound
			end
		end
	end
end)

part.TouchedEnded:Connect(function()
	local character = hitPart:FindFirstAncestorOfClass("Model")
	if character then
		if character:FindFirstChild("Humanoid") then
			debounce[character.Name] = nil
		end
	end
end)
3 Likes
local Players = game:GetService("Players")

local part = workspace.Part -- or path to part

local limbsTouchingMap = {}

part.Touched:Connect(function(hit)
	if not Players:GetPlayerFromCharacter(hit.Parent) then return end
	
	if limbsTouchingMap[hit.Parent] then
		table.insert(limbsTouchingMap[hit.Parent], hit)
	else
		limbsTouchingMap[hit.Parent] = {
			hit,
		}

		-- play sound
	end
end)

part.TouchEnded:Connect(function(hit)
	if not Players:GetPlayerFromCharacter(hit.Parent) then return end
	
	table.remove(limbsTouchingMap[hit.Parent], table.find(limbsTouchingMap[hit.Parent], hit))
	
	if #limbsTouchingMap[hit.Parent] == 0 then
		limbsTouchingMap[hit.Parent] = nil
	end
end)

This plays sound when one limb touches.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.