(Strange... it only fires one Begin and one End for me. I've found the UserInputService to sometimes fire events twice in other scenarios, however.)
To fix when Roblox is sending out duplicate events, use 'debounce'. ex, here is a modified print that will only print its argument if it's not been printed in this time frame before:
do
local args
local lastTime = -1
function printOnce(arg)
if lastTime ~= workspace.DistributedGameTime then
args = {}
lastTime = workspace.DistributedGameTime
end
if args[arg] then return end
args[arg] = true
print(arg)
end
end
printOnce(1)
printOnce(2)
printOnce(1)
wait()
printOnce(1)
To prevent having to write this code repeatedly, you might use a wrapper function like these:
function CallFuncOncePerTime(func)
local lastTime = -1
return function(...)
if lastTime == workspace.DistributedGameTime then return end
lastTime = workspace.DistributedGameTime
func(...)
end
end
function CallFuncOncePerTimeArg(func)
local lastTime = -1
local args
return function(...)
if lastTime ~= workspace.DistributedGameTime then
args = {}
lastTime = workspace.DistributedGameTime
end
local arg = {...}
arg = arg[1]
if args[arg] then return end
args[arg] = true
func(...)
end
end
function test()
print("Test")
end
test = CallFuncOncePerTime(test)
test = CallFuncOncePerTime(function()
print("Test")
end
function test(arg)
print("Test", arg)
end
test = CallFuncOncePerTimeArg(test)
test = CallFuncOncePerTimeArg(function(arg)
print("Test", arg)
end)
You can thereby modify as many functions as you need so that they all exhibit this behaviour. The idea of a wrapper function is to "wrap" a function in another function. The Roblox article on debounce gives another example of this idea (under "Advanced Notation").
2 comments
I held the keypad key for like 1-2 seconds when it printed another Enum.UserInputState.Begin. Thanks for your debounce suggestion, I'll look into it but don't think I'll make it use time (because there might be some time between the state firing a second time) but just use kind of bools like if table[key] ~= inputstate then table[key] = inputstate code() end!
That was important information you didn't mention. Anyway, you're correct that using a table like that will work. I'd use: dict[key] = true/false (recording whether the button is currently pressed down or not), and only fire the 'OnDown' function if it's not already pressed down.