Part debounce not working properly

Hello, I’m trying to make a function where if a player/character touches a part a purchase cost pops up prompting them to buy that part. And if the player leaves the part, the pop up disappears.

I created a debounce so that function isn’t fired more than once but it doesn’t seem to work properly when the player is entering/leaving the part repeatedly.

local CollectionService = game:GetService("CollectionService")

local function EnablePurchaseOfProperty(property)
	local hitbox = property.PrimaryPart
	hitbox.Touched:Connect(function(obj)
		local par = obj.Parent
		local humanoid = par:FindFirstChild("Humanoid")
		local IsCharacterTagged = CollectionService:HasTag(par, "BuyingProperty")
		if humanoid and not IsCharacterTagged then
			CollectionService:AddTag(par, "BuyingProperty")
			print("Hello, world")
			-- Show BuyingProperty Display Gui
		end
	end)
	
	hitbox.TouchEnded:Connect(function(obj)
		local par = obj.Parent
		local humanoid = par:FindFirstChild("Humanoid")
		local IsCharacterTagged = CollectionService:HasTag(par, "BuyingProperty")
		if humanoid and IsCharacterTagged then
			CollectionService:RemoveTag(par, "BuyingProperty")
		end
	end)
end

CollectionService:GetInstanceAddedSignal("Property"):Connect(EnablePurchaseOfProperty)


local function ToBuySuburbanHouse()
	local House = workspace.SuburbanHouse
	CollectionService:AddTag(House, "Property")
end


ToBuySuburbanHouse()

Is there any solution that could fix this? I thought about adding a debounce on that debounce but that seems inefficient/confusing when there’s a simpler solution out there.

A debounce would work wonderfully, just put one on the touched event. You could do something like this:

local debounce = false

hitbox.Touched:Connect(function(obj)
	if debounce then return end
	debounce = true
	
	local par = obj.Parent
	local humanoid = par:FindFirstChild("Humanoid")
	local IsCharacterTagged = CollectionService:HasTag(par, "BuyingProperty")
	if humanoid and not IsCharacterTagged then
		CollectionService:AddTag(par, "BuyingProperty")
		print("Hello, world")
		-- Show BuyingProperty Display Gui
	end

	wait(.5)
	debounce = false
end)

Typically if you have anything connected with a touched event that performs a key or intensive game function, you wanna give the touched event a debounce.

1 Like