Working with HUD, and GMod continues to crash.

I’m working on a heads up display for a game mode, and all the code works fine, no errors as far as I know. But after I added this H.U.D. today, Garry’s Mod crashes about two to four minutes after loading the game mode. About ten to twenty seconds before it crashes, the frame rate starts to drop.

Am I doing everything correctly? Is any of my code inefficient or deprecated in any way?


function DrawHealthBox(x,y,w,h,hp,armor)
	local hpmult = hp / 100
	local armult = armor / 100
	local hpred = 255
	local hpgreen = 255
	
	if (hp < 50) then
		hpred = 255
		hpgreen = 255*(hpmult*2)
	else
		hpred = 255*((1-hpmult)*2)
		hpgreen = 255
	end

	--Font
	surface.CreateFont("AdlHudFont",{font="Arial",size=16,weight=512,antialias=true})
	--Boxes and Bars.
	surface.SetDrawColor(32,32,32,127)
	surface.DrawRect(x,y,w,h)
	surface.SetDrawColor(32,32,32,192) 
	surface.DrawOutlinedRect(x,y,w,h)
	surface.SetDrawColor(0,0,0,192)
	surface.DrawRect(x+8,y+24,w-16,16)
	surface.DrawRect(x+8,y+60,w-16,16)
	surface.SetDrawColor(hpred,hpgreen,0,192)
	surface.DrawRect(x+10,y+26,((w-20)*hpmult),12)
	surface.SetDrawColor(0,255,255,192)
	surface.DrawRect(x+10,y+62,((w-20)*armult),12)
	--Draw Words.
	surface.SetFont("AdlHudFont")
	surface.SetTextColor(hpred,hpgreen,0,192)
	surface.SetTextPos(x+8,y+8)
	surface.DrawText("Health:")
	if (armor == 0) then
		surface.SetTextColor(0,0,0,192)
	else
		surface.SetTextColor(0,192,192,192)
	end
	surface.SetTextPos(x+8,y+44)
	surface.DrawText("Protection:")
end

function GM:HUDPaint()
	self.BaseClass:HUDPaint()
	local ply = LocalPlayer()
	DrawHealthBox(32,surface.ScreenHeight()-118,256,86,ply:Health(),ply:Armor())
end

Thank you.
-Buster

I don’t think you should put surface.CreateFont() in that Function because it works like a loop.

If you continuously call create font in a HUDPaint hook, you’ll eventually run out of memory and crash the game, or fill the linked list.

Call it at the top of the file.

Yeah, don’t call surface.CreateFont() inside a HUDPaint hook, just put that line to the top of the file like Acecool said, that’s also what is creating those FPS drops you’ve been getting.

Ok, makes plenty of sense. Thank you!