Entity damaging player

im trying to get entitys to deal damage to players when they get too close to them.
here is my code:
[lua]
timer.Create( “attacking”…self.Entity:EntIndex(), math.random(30,50)/10, 0, function()
for k, attack in ipairs(player.GetAll()) do
local dist = self.Entity:GetPos():Distance(attack:GetPos())
if(dist < 250 )then
attack:TakeDamage(math.random(5,7),self.Entity)
self.Entity:EmitSound(“NPC_FastZombie.LeapAttack”)
end
end
end)
[/lua]

It works, but when i spawn more then one entity, only the later one deals damage, the older one still plays the sound but no damage. Any ideas whats wrong ?

I can’t know for sure without seeing the whole code but it’s probably because of the timers.
Drop them and use ENT:Think() along with curtime to decide when to apply damage.

[lua]
function ENT:Think( )
self:NextThink( CurTime( ) + 2 ) --This makes a think happen every two seconds
local k, v

for k, v in ipairs( ents.FindInSphere( self:GetPos( ), 512 ) ) do
if v:IsPlayer( ) then
v:TakeDamage( math.random( 5, 7 ), self, self )
end
end

return true
end
[/lua]

Or something like that.

Why the “Or” and the disagree? Because that code is exactly what I described and would suggest doing. :smile:

edit: Except you shouldn’t return true or anything. This is unnecessary and I believe it could very well cause problems later.

I didn’t disagree with you. I’ve always heard you were supposed to return true when using NextThink, I just know if causes problems if you use it in a normal think ( my entity stopped thinking entirely ).

Oooooooh my bad, sorry. You are entirely right. I didn’t notice the NextThink function.

My bad. :angel:

No problem.