Problem while trying to make a gui appear when player touches a part

I’ve gotten as far as the gui opening when a player touches the part, and you can close it with a text button, but when I try touching the part again, the gui doesn’t open anymore and I can’t figure out why. Here’s my code:

local detector = script.Parent
debounce = false

detector.Touched:Connect(function(hit)
	local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
	local humanoid = hit.Parent:FindFirstChild("Humanoid")
	if humanoid and not debounce then
		debounce = true
		humanoid.WalkSpeed = 0
		plr.PlayerGui.Main.Shop.Visible = true
	end
end)

detector.TouchEnded:Connect(function(hit)
	local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
	local humanoid = hit.Parent:FindFirstChild("Humanoid")
	if humanoid and debounce then
		wait(2)
		debounce = false
	end
end)

When the player closes the gui with the text button, the gui closes and the player’s walkspeed is back to 16

Why aren’t you checking for when the Text Button is clicked, rather than when the player steps off the part?.

It’d make more sense as to set the debounce to false on the button click, rather than when they step off it.

Wouldn’t the gui just open up straight away again, as the player can’t move while the gui is open? When the debounce would become false, the player would still be on the part (as they can’t move off of it), hit it, and then the gui would open up again, or am I missing something here?

TouchEnded is a pretty “touchy” thing (haha I’m such a comedian). I’d recommend doing it through the button with remotes and also teleport the player a few studs away, as that way you’ll get a cleaner and less temperamental result.

1 Like

I recommend putting the script in the StarterGui because then you don’t have to worry so much about nil values.

Edit 2020: I’ve edited this to be functional at the very least.

You could use a LocalScript too, but in this example use a server-script to set the Enabled property of the Gui to true, keep the Gui (initially Enabled = false) under game.StarterGui and the script under the part in workspace, though canonically they should be in game.ServerScriptService.

local players = game:GetService("Players")
local part = script.Parent
local coolDown = 3
local deb

local function onTouched(t)
    if not deb then deb = not deb print("touched")
        local char = t:FindFirstAncestorOfClass("Model")
        if char and char:FindFirstChild("Humanoid") then
            local player = players:GetPlayerFromCharacter(char)
            local Gui = player.PlayerGui:WaitForChild("ScreenGui", 5)
            Gui.Enabled = true
            wait(coolDown)
            Gui.Enabled = false
            deb = false
        end
    end
end

part.Touched:Connect(onTouched)