Help with KeyCode and Touched events

Hello!

So I want my script to print the words “Button has been pressed” when it’s parent is being touched by a part named “GrabSphere” and the letter “E” is tapped on a keyboard. Everything works perfectly… Except one thing.

Even after the part named “GrabSphere” has finished touching the model, I could click E and the words “Button has been pressed” would still show up. Any way to prevent this?

Code (ServerScript)
local part = script.Parent
local uis = game:GetService("UserInputService")

local function onTouch(part)
	print("Touch started: " .. part.Name)
	if part.Name == "GrabSphere" then
		uis.InputBegan:Connect(function(keyCode)
			if keyCode.KeyCode == Enum.KeyCode.E then
				print("Button Has been pressed!")
			else
				print("Incorrect Button")
			end
		end)
	end
end

local function onTouchEnded(part)
	print("Touch ended: " .. part.Name)
	if part.Name == "GrabSphere" then
	end
end

part.Touched:Connect(onTouch)
part.TouchEnded:Connect(onTouchEnded)
Explorer

The script “Gun Handler” is the one with the code in it. The other script is irrelevant.

Annotation 2020-08-02 120724

Output

The output “Incorrect Button” was just me spamming a button that was not E.

Annotation 2020-08-02 1207241

Im sure this is an easy fix and I am forgetting something crucial lol.

Try separating the events, and having a variable keep track of whether or not the part is touching.

local part = script.Parent
local uis = game:GetService("UserInputService")
local isTouching = false

local function onTouch(part)
	print("Touch started: " .. part.Name)
	if part.Name == "GrabSphere" then
		isTouching = true
	end
end

local function onTouchEnded(part)
	print("Touch ended: " .. part.Name)
	if part.Name == "GrabSphere" then
		isTouching = false
	end
end

uis.InputBegan:Connect(function(keyCode)
	if keyCode.KeyCode == Enum.KeyCode.E and isTouching then
		print("Button Has been pressed!")
	else
		print("Incorrect Button")
	end
end)

part.Touched:Connect(onTouch)
part.TouchEnded:Connect(onTouchEnded)
1 Like

Thanks so much for helping me out!