Making a SWEP with auto replenishing ammo

I’m trying to make a simple SWEP with ammo that auto replenishes, much like the airboat gun from HL2.

The gun will have 3 ammo, and 1 ammo will replenish every second.

Right now I’m just using this code in the think hook:

[LUA]SWEP.Primary.ClipSize = 3
SWEP.Primary.DefaultClip = 3
SWEP.Primary.Automatic = true
SWEP.Primary.Ammo = “Pistol”
SWEP.ReloadCooldown = false

function SWEP:Think()
if CLIENT then return end

if (not self.ReloadCooldown) and self:Clip1() ~= 3 then
self.ReloadCooldown = true
print( “Running reload” )
self:GetOwner():GiveAmmo(1, “Pistol”)
timer.Simple(1, function() self.ReloadCooldown = false end)

However, this isn’t a very good solution because the player can still manually reload whenever.

Is there a way to just set the primary ammo that is in the gun, without having to give the player ammo that has to be reloaded in?

The player never needs to pick up ammo so I suppose using an ammo type is not needed, I just wanted to use the SWEP ammo system so that all the default functions for getting amount of ammo etc. would work.

You can use SetClip, but you’ll want to do it shared for prediction. Also, there’s no need to use a timer in a Think hook, just have a variable that keeps track of time.

Thanks, SetClip1 works perfectly, here is my updated code:

[LUA]function SWEP:Think()
if self:Clip1() ~= 3 then
if not self.ReloadCooldown then
self.ReloadCooldown = true
self.NextReload = CurTime() + 1.5
elseif self.NextReload <= CurTime() then
self:SetClip1(self:Clip1() + 1)
self.ReloadCooldown = false

function SWEP:Reload()
return false

Thanks for letting me know about prediction too, the wiki page has a lot of useful information.

One last question though, is there any way to either a) Show the ammo display while having ammo set to “none” (the gun still works when using SetClip) or b) to remove the second number showing the total ammo? I’ve changed the ammo type to AirboatGun so the player doesn’t start with any, but the second number is still shown.


You can make just the second number disappear by setting SWEP.Primary.ClipSize to -1 and converting all of your code to use the DefaultClip/GiveAmmo.