My frame keeps appearing without clicking the button

So I have basically made a thing where when you click E on your keyboard and if your touching a specific part, it makes a Frame appear (for NPC intereactions) although when I try it out in game, it works but, after touching the part once, even if it get out of the zone, after clicking E the frame still appears. Any help is apreciated. Here is my script:

local Part = game.Workspace.MusPart

local frame = game.Players.LocalPlayer.PlayerGui:WaitForChild("SpeechGui").Mus
local cd = false

local Players = game:GetService("Players")
local UserInputService = game:GetService("UserInputService")

local Order = frame.Order

Part.Touched:Connect(function(hit)
	UserInputService.InputBegan:Connect(function(input)
		if input.UserInputType == Enum.UserInputType.Keyboard then
			if input.KeyCode == Enum.KeyCode.E then
				if cd == false then
						if hit.Parent.Humanoid then
						cd = true
						if frame.Visible == false then
							Order.Value = 1
							frame.Visible = true
							frame.Parent.Intereact.Visible = false
						
						end
						wait(1)
						cd = false
					end
				end
			end
		end
	end)
end)

And I forgot to mention this but I am not using proximity prompts because I put in a custom one that appears when you touch the part.

Try this:

--//Services
local Players = game:GetService("Players")
local UserInputService = game:GetService("UserInputService")

--//Variables
local LocalPlayer = Players.LocalPlayer
local PlayerGui = LocalPlayer:WaitForChild("PlayerGui")
local Frame = PlayerGui:WaitForChild("SpeechGui").Mus
local Order = Frame.Order
local Part = workspace.MusPart

--//Controls
local debounce = false

--//Tables
local Connections = {}

--//Functions
Part.Touched:Connect(function(hit)
	local player = Players:GetPlayerFromCharacter(hit.Parent)

	if player and player == LocalPlayer then
		Connections.InputBegan = UserInputService.InputBegan:Connect(function(input)
			if input.UserInputType == Enum.UserInputType.Keyboard and input.KeyCode == Enum.KeyCode.E and not debounce then
				debounce = true

				if not Frame.Visible then
					Order.Value = 1
					Frame.Visible = true
					Frame.Parent.Intereact.Visible = false
				end

				task.wait(1)
				debounce = false
			end
		end)
	end
end)

Part.TouchEnded:Connect(function(hit)
	local player = Players:GetPlayerFromCharacter(hit.Parent)

	if player and player == LocalPlayer then
		Connections.InputBegan:Disconnect()
	end
end)

I optimized your code and also fixed it. The way to stop functions from running is to disconnect them.

It’s still giving me the same problem sadly

Instead of creating a connection to the UserInputService’s ‘InputBegan’ event/signal use the following API method to check if or not a keyboard’s ‘E’ key is being held down.

if UserInputService:IsKeyDown(Enum.KeyCode.E) then
1 Like