Simple Percent Funtion

I’m trying to figure out how to make some text on the screen that goes up by 5 seconds.

Here’s what I have so far:



percent = 0


local PercentText = vgui.Create( "DLabel" )
	PercentText:SetPos(100, 100) 
	PercentText:SetText( percent.."%" )

local delay = 0
hook.Add( "Think", "CurTimeDelay", function()
 if CurTime() < delay then return end
	percent = percent + 1
	PercentText:Refresh()
	delay = CurTime() + 5
 end )

With this the text appears, however the number does not go up. What am I doing wrong?



PercentText = vgui.Create( "DLabel" )
PercentText:SetPos(100, 100) 
PercentText:SetText( percent.."%" )
PercentText.TimeCycle = 5
PercentText.Percent = 0

timer.Create( 'Timer.DLabel.UpdatePrecentage', PercentText.TimeCycle, 100 / PercentText.TimeCycle, function()
      if PercentText && PercentText.Percent && PercentText.Percent < 100 then
         PercentText.Percent = math.Clamp( PercentText.Percent + 1, 0, 100 )
         PercentText:SetText( PercentText.Percent .. "%" )

          return
     end
     
     timer.Destory( 'Timer.DLabel.UpdatePrecentage' )
end)


This is probably still a shitty way, but if you want to be fancy you can do a similar approach using the VGUI elements Think/Paint functions to Lerp to all together (so that it looks cool and smoothly counts up instead of just 1 -> 2 -> etc)

I reccomend this way:



local time

hook.Add( "HUDPaint", "CurTimeDelay", function()

	if not time then time = CurTime() end

	surface.SetFont( "DermaDefault" )
	surface.SetTextColor( 255, 255, 255, 255 )
	surface.SetTextPos( 100, 100 )
	local percent = math.Clamp( ( CurTime() - time ) / 5 * 100, 0, 100 )
	surface.DrawText( percent .. "%" )

end )


It doesn’t do anything dodgy like adding 1 onto a number every frame (which is obviously dependant on the user’s hardware speed), and will always give accurate results.
It also doesn’t use any unnecessary timers, it just uses the way more simple and way more logical method of using a single variable.

Whenever you want the timer to restart, you simply need to run:



time = CurTime()


[editline]20th August 2017[/editline]

If you want this to work for a DLabel (which I don’t reccomend because of the frequent updating), then it’s just a matter of doing the exact same thing:



local PercentText = vgui.Create( "DLabel" )
PercentText:SetPos( 100, 100 )
PercentText:SetText( "0%" )

hook.Add( "HUDPaint", "CurTimeDelay", function()

	if not PercentText.Time then PercentText.Time = CurTime() end

	local percent = math.Clamp( ( CurTime() - PercentText.Time ) / 5 * 100, 0, 100 )
	PercentText:SetText( percent .. "%" )

end )