# Npc Killing for xp

hay guys/girls i need some help heres the code if you can modify it thanks

``````

function GM:OnNPCKilled( victem, killer, weapon)

local rand = math.random( 1, 10 )
local xpdrop

if rand == 1 then
xpdrop = self:SetNWInt("xp") + 1
elseif rand == 2 then
xpdrop = self:SetNWInt("xp") + 2
elseif rand == 3 then
xpdrop = self:SetNWInt("xp") + 3
elseif rand == 4 then
xpdrop = self:SetNWInt("xp") + 4
elseif rand == 5 then
xpdrop = self:SetNWInt("xp") + 5
elseif rand == 6 then
xpdrop = self:SetNWInt("xp") + 6
elseif rand == 7 then
xpdrop = self:SetNWInt("xp") + 7
elseif rand == 8 then
xpdrop = self:SetNWInt("xp") + 8
elseif rand == 9 then
xpdrop = self:SetNWInt("xp") + 9
elseif rand == 10 then
xpdrop = self:SetNWInt("xp") + 10
end

end

``````

what exactly do you need help with?

uhhh… well im trying to get it to add xp to the xp database i made

Well for starters don’t use self. It doesn’t represent any player object. From what I can tell you’ll want to use killer instead.

Next you can simplify (and correct) the code by using
[lua]
function GM:OnNPCKilled( victim, killer, weapon )
local rand = math.random( 1, 10 )
killer:SetNWInt(“xp”, killer:GetNWInt(“xp”) + rand )
end
[/lua]

SetNWInt needs two arguments, the string representing which integer to change, and what to change it to. First argument is “xp” to change xp, and second adds their current “xp” integer with the rand variable created with math.random.

``````

local rand = math.random(1, 10)

function XPGainNpc(npc, killer, weapon)
if killer:IsPlayer() and npc:IsNPC() then
killer:SetNWInt("xp",killer:GetNWInt("xp") + rand)
end
end
end

``````

-ninja´d too.

Thank you so much now i can finsh my gamemode!

Snorlaxs brings up a good point, you should check that killer is actually a player, but you don’t need to check the NPC because the hook wouldn’t be called in the first place if the victim wasn’t a NPC.

Use:
[lua]
function GM:OnNPCKilled( victim, killer, weapon )
if killer:IsPlayer() then
local rand = math.random( 1, 10 )
killer:SetNWInt(“xp”, killer:GetNWInt(“xp”) + rand )
end
end
[/lua]

XRayhunter what gamemode is you making? And just put this in a addon and not gamemode so you can use it on all gamemodes (If it dont conflict)