i wantt to get how long someone has held for for but i want it to be live, not after he lets go, so it updates the timer as they are holding down, not updating it after they have held down, i need this for a bow projective prediction system
Held what down for? If you mean a key or the mouse, create an isHolding and a timer variable, listen for the InputBegan, check if the input the player pressed is the one your listening for, if it is, enable the isHolding variable, also listen for the InputEnded variable, if the input the player stopped holding is the one your listening for, disable the isHolding variable and set the timer to 0.
Create a while loop that runs while the isHolding variable is true, wait(0.01) everytime the while loop runs, then add 0.01 to the timer, then u can check if the timer has reached a certain point using an if statement and then do whatever you want it to do.
the only problem with that is using wait(0.01) because wait is deprecated and the minimum wait time is 0.03 so it would be waiting 0.03 but adding only 0.01
to solve that problem simply use task.wait(0.015) and add 0.015 to the timer
You can check about task.wait and wait here → About task.wait()
Hopefully I understand this correctly, but here goes. You can make great use of tick:
local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")
local isHeld = false
local heldTime = nil
UserInputService.InputBegan:Connect(function(input, gpe)
if gpe then return end
if input.UserInputType == Enum.UserInputType.MouseButton1 then
isHeld = true -- start holding
heldTime = tick() -- tick() is VERY useful for this
while RunService.Stepped:Wait() do -- in this case, a while loop works better than a repeat
if isHeld then
print(tick() - heldTime) -- subtract current time from initial time
else
break
end
end
end
end)
UserInputService.InputEnded:Connect(function(input, gpe)
if gpe then return end
if input.UserInputType == Enum.UserInputType.MouseButton1 then
isHeld = false -- not held anymore
heldTime = tick() - heldTime
warn("Final time:", heldTime, "seconds")
end
end)
If you’d like to make it look nicer, you could round the numbers so there are no decimals
tick() - heldTime
-- example: 2.348430871963501 seconds
math.round(tick() - heldTime)
-- example: 2 seconds
and you can replace while game:GetService("RunService").Stepped:Wait() do
with while wait(1) do
Hope this helps!