Debounce variable not working properly

Hello, I have a gamepass door in my game and I included a debounce in my script. However the debounce does not seem to be working properly
The script

local mps = game:GetService("MarketplaceService")

local debounce = false

script.Parent.Touched:Connect(function(hit)
	if debounce == false then
        print("debounce is false")
		debounce = true
		if hit.Parent:FindFirstChild("Humanoid") then
			local player = game.Players:GetPlayerFromCharacter(hit.Parent)
			print(player)
			if mps:UserOwnsGamePassAsync(player.UserId,11828899) then
				script.Parent.CanCollide = false
				print("Player owns gamepass")
				wait(2)
				script.Parent.CanCollide = true
				debounce = false
			else
				print("Player does not own gamepass")
				mps:PromptGamePassPurchase(player.UserId,11828899)
				wait(10)
				debounce = false
			end
		end
	elseif debounce == true then
		print("Debounce is true") --Included this after problems started arising
		wait(10)
	else
		print("Debounce has error") --Included this after problems started arising
	end
end)

The debounce actually worked at first but today it does not seem like it is working.
The output:

  Debounce is false --Ignore this as this as the script decided to print this out when I am joining. So as the first true debounce print
  Debounce is true (x1079)
17:50:49.216 - Disconnect from ::ffff:127.0.0.1|51173

And for some reason, it always prints the debounce check when I am joining and nobody else is touching it。

So what is wrong with the script?

2 Likes

There’s a lot of issues with this code. On line 8, you set debounce to true but never release it in the event that a Humanoid was not found. This means that if anything that isn’t a player were to hit your part, the debounce would stay true forever. On line 10, you use GetPlayerFromCharacter which might return nil if an NPC were to touch the part. You should use an if-statement to verify that the function actually turned a non-nil value. Line 12 also poses an issue since async functions can fail, it should be wrapped in pcall to prevent an error from breaking your game logic. Additionally, you should cache the result since you can assume if they own the gamepass once, they will always own it.

2 Likes

I have checked the part’s surroundings and no npc touches the part. Only the floor and the frames around it.(When I say frames I mean like door frames)