SWEP Ammo Limit

Ive got a swep gun that spawns npc’s. I have it configured for a 5 second delay between “shots” and i have 7 ammo set. But the gun can spawn npc’s without delay an infinite number of times (even though the ammo decreases to 0). Any idea how to fix this?


function SWEP:PrimaryAttack()
	// This is the position your looking at
	local eyetrace = self.Owner:GetEyeTrace() 	

	self.BaseClass.ShootEffects (self);
	
	// The rest is only done on the server
	if (!SERVER) then return end
	
	// Make a fastzombie
	local ent = ents.Create( "npc_fastzombie" )
		ent:SetPos( eyetrace.HitPos )
	ent:Spawn()
	
	self:TakePrimaryAmmo( 1 )
	
end

[lua]self:SetNextPrimaryFire( CurTime() + self.Primary.Delay )[/lua]

and

[lua]function SWEP:CanPrimaryAttack()

if (self.Weapon:Clip1() <= 0) then
	self.Weapon:SetNextPrimaryFire(CurTime() + 0.5)
	return false
end

return true
end[/lua]

Awesome, Thanks!

[editline]20th January 2013[/editline]

Ugh, the code works great but once there’s no more ammo left, i can create npc’s an infinite number of times without any delay.



function SWEP:PrimaryAttack()
	// This is the position your looking at
	local eyetrace = self.Owner:GetEyeTrace() 	

	self.BaseClass.ShootEffects (self);
	
	// The rest is only done on the server
	if (!SERVER) then return end
	
	// Make a fastzombie
	local ent = ents.Create( "npc_headcrab" )
		ent:SetPos( eyetrace.HitPos )
	ent:Spawn()
	
	self:SetNextPrimaryFire( CurTime() + self.Primary.Delay )
	
	self:TakePrimaryAmmo( 1 )
	
	if (self.Weapon:Clip1() <= 0) then
        self.Weapon:SetNextPrimaryFire(CurTime() + 0.5)
        return false
    end
	
return true
end


You’re checking if they have ammo less than 0 after taking ammo… This should be above everything, alongside the SetNextPrimaryFire.

I did that but its only partially working. NPC’s are finally spawning with the delay, but once there’s no more ammo, they can keep being spawned forever (but with the delay).

Use the CanPrimaryAttack function.