How would I make a function fire once?

Hello there fellow Developers.

So, I was recently creating a script, where if you are near a part and press F, something will be printed. I tried 2 different ways. However, with both of my approaches, i had the same error. The function would fire multiple times, and I would end up with “Hello World” printed 50 times when I hit F.

In my first attempt I tried to calculate the magnitude between the player’s Torso and Jack’s (the object that you should be near). Then I made it so if the magnitude is smaller than a number, then the User Input Function will be ready to use.

Here is the first code I used:

local part = workspace.TutorialPart
local UIS = game:GetService("UserInputService")
local Gui = workspace.Jack.UpperTorso.BillboardGui
local Jack = workspace.Jack.LowerTorso
local plr = game.Players.LocalPlayer
local char = plr.Character or plr.CharacterAdded:Wait()
local Torso = char:WaitForChild("LowerTorso")


while wait() do 
	local magnitude = (Jack.Position - Torso.Position).Magnitude
	
	if magnitude < 5.0078711509705 then 
		Gui.Enabled = true
		
		UIS.InputBegan:Connect(function(i, v)
			if i.KeyCode == Enum.KeyCode.F then
				print("F was pressed")		
			end
		end)
	end
end

In the second attempt, I created a part around Jack, and then I created a part.Touched function, which would enable the User Input function. It didn’t work either.

Here is the code I used:

local part = workspace.TutorialPart
local UIS = game:GetService("UserInputService")
local Gui = workspace.Jack.UpperTorso.BillboardGui

Gui.Enabled = false

local function Start()
	print("F was pressed")
end

part.Touched:Connect(function()
	UIS.InputBegan:Connect(function(inputObject, gameProscessedEvent)
		if inputObject.KeyCode == Enum.KeyCode.F then
			Start()
		end
	end)
end)

This is the message I get:
Screenshot 2020-08-22 at 12.47.03 AM

Any solutions?

Regards,
Theyoloman1920

P.S.: I will test and reply to your suggestions tomorrow, as it’s night time in my time zone.

Oh my God. You are connecting a new function several times a second!

Remove your while wait() do.

Inside UIS.InputBegan:Connect(function()) check for the magnitude. If magnitude is less than your desired value, enable the gui.
You might also want to add a debounce to that to stop people from spamming the key.

Here is a quick example.

local part = workspace.TutorialPart
local UIS = game:GetService("UserInputService")
local Gui = workspace.Jack.UpperTorso.BillboardGui
local Jack = workspace.Jack.LowerTorso
local plr = game.Players.LocalPlayer
local char = plr.Character or plr.CharacterAdded:Wait()
local Torso = char:WaitForChild("LowerTorso")


UIS.InputBegan:Connect(function(i, v)
	local magnitude = (Jack.Position - Torso.Position).Magnitude
	
	if magnitude < 5.0078711509705 then 
		Gui.Enabled = true
		if i.KeyCode == Enum.KeyCode.F then
			print("F was pressed")
		end
	end
end)
3 Likes