Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Why is a function being ran twice when a key is only clicked once?

I am scripting something, but it is becoming an issue since the function is running itself twice, it is basically cancelling itself out (irrelevant). Here is the code:

local player = game:GetService("Players").LocalPlayer
local car = script.Parent.Value.Value
local Revent = car.RBlinker
local Levent = car.LBlinker
local Head = car.HeadLights
player:GetMouse().KeyDown:connect(function(key)
	key = string.upper(key)
	if key == "E" then
		Revent:FireServer()
		print("fired")
	end
end)

When the key "E" is pressed once on my keyboard, the output shows that the function has been fired twice, as "fired" appears twice. I also put a print on the server script waiting for the remote event to be fire, it is printing it twice as it is being fried twice. Anyone know why this is happening, and how to fix it?

1 answer

Add a debounce in your script. Also learn how to use UserInputService, it's easier and will work better in the long run versus keydown.

However for your code and the debounce:

local player = game:GetService("Players").LocalPlayer
local car = script.Parent.Value.Value
local Revent = car.RBlinker
local Levent = car.LBlinker
local Head = car.HeadLights
local debounce = false
	player:GetMouse().KeyDown:Connect(function(key)
		key = string.upper(key)
			 if key == "E" then
				if debounce == false then
					debounce = true
			      	 	Revent:FireServer()
			        	print("fired")
					wait(3)
					debounce = false  -- will make the script functional again after 3 seconds
		   	 end
		end
	end)

2 comments

0

@Radstar1 That does not seem to work, as the function is still being ran twice.

0

i just edited the script I sent you,try that instead.

This discussion is preserved as it was. New answers, comments, and votes are closed.