Handling Debounce for Multiple Identical Client-Side Objects

I’ve created a collectibles system in a game that spawns in collectibles that stay for other players even after they are collected by someone else. Inside each collectible is a server script that fires the client and has the client turn it invisible, play a sound, and wait a certain time before being available again. The problem arises when I implement a debounce in the client-side script. The debounce prevents the player from collecting other identical collectibles because it waits for the spawn timer to finish before turning the debounce off and letting the player collect it again. The local script is located in StarterPlayerScripts. I am wondering how I could handle this.

--Server Script
function onTouch(hit)
	if hit.Parent:findFirstChild("Humanoid") ~= nil then
		if game.Players:findFirstChild(hit.Parent.Name) ~= nil then
			local player = game.Players:GetPlayerFromCharacter(hit.Parent)
			game.ReplicatedStorage.RemoteEvents.IceTouched:FireClient(player,script.Parent,player)
		end
	end
end
script.Parent.Touched:connect(onTouch)

--Client Script
local Players = game:GetService("Players")
local LocalPlayer = Players.LocalPlayer

debounce = false
local function Touched(ice, player)
    if (player == LocalPlayer) and not debounce then
	    debounce = true
		ice.Transparency = 1
		ice.CanCollide = false
		ice.Rays.Enabled = false
		script.Sound:Play()
		game.ReplicatedStorage.RemoteEvents.IceCollected:FireServer(LocalPlayer)
		wait(math.random(game.ReplicatedStorage.IceLowerBound.Value,game.ReplicatedStorage.IceUpperBound.Value))
		ice.Transparency = 0.3
		ice.CanCollide = true
		ice.Rays.Enabled = true
		debounce = false
    end
end

game.ReplicatedStorage.RemoteEvents.IceTouched.OnClientEvent:Connect(Touched)
1 Like

You could store unique debounce values for each instance of ice, in a dictionary.

Example:

local ice_debounces = {} --//Dictionary we can store instances of ice In to keep track of
local function Touched(ice, player)
    if (player == LocalPlayer) and not ice_debounces[ice] then
	    ice_debounces[ice] = true --//Assuming ice is a part
		ice.Transparency = 1
		ice.CanCollide = false
		ice.Rays.Enabled = false
		script.Sound:Play()
		game.ReplicatedStorage.RemoteEvents.IceCollected:FireServer(LocalPlayer)
		wait(math.random(game.ReplicatedStorage.IceLowerBound.Value,game.ReplicatedStorage.IceUpperBound.Value))
		ice.Transparency = 0.3
		ice.CanCollide = true
		ice.Rays.Enabled = true
		ice_debounces[ice] = nil --//Reset the debounce for this unique part
    end
end

Hope this helps.

4 Likes

This definitely helped, it worked perfectly. Thank you

2 Likes