Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 7 years ago

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

Log in to vote
0
Answered by
Radstar1 270 Moderation Voter
7 years ago
Edited 7 years ago

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)
0
@Radstar1 That does not seem to work, as the function is still being ran twice. CodedWealth 21 — 7y
0
i just edited the script I sent you,try that instead. Radstar1 270 — 7y
Ad

Answer this question