How do I prevent to award player multiple times before the debounce is set to true?

Hey. I made a coin, and I used a touched event.
Each time a lower torso is hitting it, the player is being awarded 2 coins and the debounce goes to true and it can no longer award the player coins.
But, the player hits the coins multiple times so fast that until the debounce is being set to true it fires multiple times and awards him more. What can I do to prevent it?
Here’s my code:

local debounce = false

function on_Touch(hit)

	if not debounce then
		
		if hit.Name == "LowerTorso" then
			
			debounce = true
			
			local succed, failed = pcall(function()
					
				local character = hit.Parent
				
				local coinSound = script.Parent.CoinSound
				
				coinSound.Parent = character.UpperTorso
				
				coinSound:Play()
				
				local player = game.Players:GetPlayerFromCharacter(character)
				
				local leaderstats = player.leaderstats
				
				local coinsValue = leaderstats.Coins.Value
				
				local add = 2
				
				local result = coinsValue + tonumber(add)
				
				leaderstats.Coins.Value = result
				
				script.Parent:Destroy()
				
				if hit then
					
					local player = game.Players:GetPlayerFromCharacter(hit.Parent)
						
					player.PlayerGui.Coin.Enabled = true
					
					wait(1)
					
					player.PlayerGui.Coin.Enabled = false
					
					coinSound:Destroy()
			   end
			end)
			
			if succed then
				
				warn("Succed.")
			else
				warn("Failed; retrying")
			end
		end
	end
end

script.Parent.Touched:Connect(on_Touch)

Show us your code, you could be missing out on yielding appropriately or implementing debounce for your case slightly incorrectly.

Try shifting the wait(1) to right before the second-last end.

1 Like

I shared my code above, it’s a server script.
Do you see any error?

I tested a reduced version of the code. The fundamentals seem fine, so it’s leaving me to wonder if you may be spawning more than one coin in the same position?

This is what I ran:

Code
local debounce = false

function on_Touch(hit)

	if not debounce then
	
		if hit.Name == "LowerTorso" then
		
			debounce = true
				
			local character = hit.Parent
		
			local player = game.Players:GetPlayerFromCharacter(character)
		
			print("give coins")
		
			script.Parent:Destroy()
				
			print("coin gui on")
			
			wait(1)
			
			print("coin gui off")
		end
	end
end

script.Parent.Touched:Connect(on_Touch)

Sadly, it does not spawn at the same place.
Thanks for trying to help though.