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

If Player Holds E for 5 seconds, a Print Appears?

I don't get any errors, but as Soon as I press E, it prints "Hi" and not when I hold for 5 seconds :#

local UIS = game:GetService("UserInputService")
local Humanoid = game.Players.LocalPlayer.Character:WaitForChild("HumanoidRootPart")
local part = workspace.joinTable

local Start = tick()

UIS.InputBegan:Connect(function(key)
	if key.KeyCode == Enum.KeyCode.E then
if (part.Position - Humanoid.Position).magnitude < 10 then
 if tick() - Start >= 5 then
	print("hi")
end
end
end
end)

1 answer

✓ Accepted answer

This is because you call tick() at the start of your code, so if you wait +5 seconds after spawning in, the condition passes immediately. A solution to this would be to use a while loop + the UserInputService:IsKeyDown method.

UIS.InputBegan:Connect(function(Key, Process)
    if (Process) then return nil end;

	if (Key.KeyCode == Enum.KeyCode.E) then
		local dt = 0;
	    while ( (part.Position - Humanoid.Position).magnitude < 10) and UIS:IsKeyDown(Key.KeyCode) do
			if (dt >= 5) then 
	            print("hi")
				break;
	        end
	        dt = dt + game:GetService('RunService').RenderStepped:Wait();
	    end
	end
	
end)

RenderStepped:Wait() returns a number value, by the way.

2 comments

0

I hold E, and it doesn't work :/ I don't get any print or any errors

0

May or may not made it so the function would only run if they were typing in a textbox. Anywho, fixed.

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