Portal stops working after multiple uses

So I have a portal in my game, it basically teleports the player into the map, along with clearing their backpack and giving them a specific tool, but I found that during testing, after some uses of it, it just completely stops teleporting people or working at all. Heres my code:

local Players = game:GetService("Players")
local RESET_SECONDS = 2
local isTouched = false

local function removeItems(player)
	local Backpack = player.Backpack
	local Character = player.Character or player.CharacterAdded:Wait()
	local GearInPlayer = player:FindFirstChild("Backpack")
	local GearInCharacter = Character:GetChildren()

	GearInPlayer:ClearAllChildren()
	for _, Tool in pairs(GearInCharacter) do
		if Tool:IsA("Tool") then
			Tool:Destroy()
		end
	end
end

local function Touch(hit)
	if not isTouched then
		isTouched = true

		local player = Players:GetPlayerFromCharacter(hit.Parent)
		local Tool = player.leaderstats.Pan.Value
		local Pos = game.Workspace.TeleLocation

		if player then
			removeItems(player)
			wait(.1)
			local ChosenTool = game.ServerStorage.Pans:FindFirstChild(Tool):Clone()
			ChosenTool.Parent = player.Backpack
			hit.Parent:moveTo(Pos.Position)
			wait(RESET_SECONDS)
			isTouched = false
		else
			warn("This portal is on cooldown")
		end
	end
end

script.Parent.Touched:Connect(Touch)

The isTouched variable is set to true when the part is touched and set to false after waiting but only if the part that touched it is the character of a player. Put isTouched = true under if player then.

3 Likes

Replace this

if player then
			removeItems(player)
			wait(.1)
			local ChosenTool = game.ServerStorage.Pans:FindFirstChild(Tool):Clone()
			ChosenTool.Parent = player.Backpack
			hit.Parent:moveTo(Pos.Position)
			wait(RESET_SECONDS)
			isTouched = false
		else
			warn("This portal is on cooldown")
		end

with

if player then
		removeItems(player)
		wait(.1)
		local ChosenTool = game.ServerStorage.Pans:FindFirstChild(Tool):Clone()
		ChosenTool.Parent = player.Backpack
		hit.Parent:moveTo(Pos.Position)
		wait(RESET_SECONDS)	
else
		warn("This portal is on cooldown")
end
isTouched = false
1 Like

Thank you, both replies helped, I just forgot to check on them. Thanks anyways!