I am creating a custom HUD and i am getting this error:
[ERROR] addons/darkrpmodification-master/lua/darkrp_modules/custom-hud/cl_hud.lua:132: attempt to call method 'GetActiveWeapon' (a nil value)
1. fn - addons/darkrpmodification-master/lua/darkrp_modules/custom-hud/cl_hud.lua:132
2. unknown - addons/ulib-v2_63/lua/ulib/shared/hook.lua:109
This is the part that is causing the problem:
local ply = LocalPlayer() function testHUDammo()
if ply:GetActiveWeapon():Clip1() == -1 then return end
if (ply:GetActiveWeapon():IsValid()) then
local mag_current = ply:GetActiveWeapon():Clip1()
local mag_extra = ply:GetAmmoCount(ply:GetActiveWeapon():GetPrimaryAmmoType())
DrawBlurRect( ScrW()-220, ScrH()-120, 200 ,100)
draw.SimpleText("Ammo:","Arialtwo",ScrW()-210,ScrH()-110,Color(255,255,255))
draw.SimpleText(mag_current.." / "..mag_extra,"Arialtwobig",ScrW()-120,ScrH()-85,Color(212, 244, 66),TEXT_ALIGN_CENTER)
end
end
hook.Add("HUDPaint", "Ammohud", testHUDammo)
If you know anything that could be causing this i would appreciate your advice.
This is likely caused because you're assigning LocalPlayer() too early. It will probably get garbage collected before it's used. It's good practice to define local variables only at the scope in which they're needed, so:
local ply = LocalPlayer()
should go at the top of the function, not outside it. Also, it's a good idea to check if the player is valid before calling any methods on it, so adding this at the top:
if !IsValid(ply) then return end
would add an extra line of protection against script errors.
Fixed it, many thanks.
Sorry, you need to Log In to post a reply to this thread.