Adding a Local Debounce

Hey!

I’m trying to create a part that sends a system message into the chat (for everyone to see) when touched. This is supposed to work for all players, and it should only send the message one time.

I’m having trouble adding a “local” debounce so that all players can touch it, but it’ll only send the system message once for each player (who touches the part).

The portion where the message is sent works perfectly fine with the use of a RemoteEvent, but I’m just having trouble with adding the debounce in a server script.

The code included below is located in a server script inside of a part. It’s what I have so far, but it doesn’t work properly. The debounce is server-wide (therefore preventing other players from having their own system message sent if another player has touched it before them), but I would like it to be local using the touch function somehow.

Code
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local SendMessageEvent = ReplicatedStorage:WaitForChild("SendSystemChatMessage")

local color = BrickColor.new("Really red").Color

local debounce = false

script.Parent.Touched:Connect(function(hit)
	
	if hit.Parent:FindFirstChild("Humanoid") then
		
		local player = game.Players:GetPlayerFromCharacter(hit.Parent)
		local message = "[SYSTEM]: " .. player.Name .. " has touched the part."
		
		if debounce == false then
			SendMessageEvent:FireAllClients(message, color)
			debounce = true
		end	

	end
	
end)

I’ve already looked at some of the topics on the forum and some documentation pages on the Developer Hub (which is how I learned what debounces were in the first place), but I can’t seem to find a topic specific to incorporating a debounce locally.

I appreciate anyone’s help! Thank you for reading.

2 Likes

You could just implement a table of players that have already touched the event :thinking:

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local SendMessageEvent = ReplicatedStorage:WaitForChild("SendSystemChatMessage")
local color = BrickColor.new("Really red").Color
local PlayerTable = {}

script.Parent.Touched:Connect(function(hit)
	if hit.Parent:FindFirstChild("Humanoid") then
		
		local player = game.Players:GetPlayerFromCharacter(hit.Parent)
		local message = "[SYSTEM]: " .. player.Name .. " has touched the part."
		
		if not table.find(PlayerTable, player) then --Checking if the Player is not inside the table to fire the event on
            PlayerTable[player] = true --This will insert the Player into the table to prevent that specific player from firing the event again
			SendMessageEvent:FireAllClients(message, color)
			debounce = true
		end	
	end
end)
2 Likes

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