How to know for how long a player is holding something

I want to “record” the value for how long a player has been holding something so that I can use that value for other statements. I found something on the forum but it is only for detecting if a player is holding the tool. Thank you.

For this instance, you’re going to use Equipped to start a timer. Unequipped for stopping it. The timer is most likely using os.time() as starting and os.time() again(a new call) to get the new time after it was unequipped. Add it to the total time held.

3 Likes
local timeHeld = 0


tool.Unequipped:Connect(function()
        timeHeld = timeHeld + (os.clock() - timeHeld)
end)

this would work for temporary calculations but if your wanting a long term time that saves, then you’ll want to consider a different approach with the server and think about the differences between os.time(), os.clock(), tick() etc or even use external time servers with http request.

1 Like

Do I have to put it in a code that detects whether a player is holding a tool?

no, only when they stop holding it.

I’m confused, how can I make it so that it counts while the player is holding it ?

are you wanting it to constantly increment while they are holding it?

or do you just want to add to a total when they stop holding it?

1 Like

To constantly increment. Cause I want something to happen if a player has been holding something for a certain amount of time

1 Like

oh, ok

local timeHeld = 0
local holding=false

tool.Equipped:Connect(function()
    holding=true
    while(holding)do
        timeHeld = timeHeld + (os.clock() - timeHeld)
        rs.Heartbeat:Wait()
    end
end)


tool.Equipped:Connect(function()
   holding=false
end)

now you can something like

if(timeHeld >= 5) then
    --do something
end

i would consider handling the time changes/checks on the server though, using a remote to event start it when player unequips or equips a tool, and you may not even need to constantly increment for this, depending on what your using the time for.

1 Like

Thank you for that. Unfortunately I do need a constant increment since I don’t want a player holding something for too long xd

np and all good, do whatcha gotta do.

1 Like