Avatar Image Help

Hello there I’ve ran into a problem recently when drawing and removing the Avatar panel.

My setup, Press KEY to draw HUD, when KEY is released, the HUD is no longer being drawn. (Works)

What doesn’t work is removing/making the avatar invisible when the key is released. My Avatar is not being drawn in my HUD, for it is not being drawn every frame.
If anyone can come up with a solution that would be great!

code?




function Avatar()
	if input.IsKeyDown( KEY )  then 
	local av = vgui.Create("AvatarImage")
	av:SetPlayer( LocalPlayer(), 64 )
	av:SetSize(64, 64)
	av:SetPos(x / 2, y - 400)
	av:ParentToHUD()
	end
end



hook.Add("HUDPaint", "PlayerPanel", function() 
local ply = LocalPlayer()
 if HoldToOpen == true and
 input.IsKeyDown( KEY ) then
 	surface.SetDrawColor(PBackGround)
	surface.DrawTexturedRect( x - 880 - 2, y - 150 - 2, 400 + 4, 140 + 4)
	surface.SetDrawColor(PBackGround2)
	surface.DrawTexturedRect( x - 880, y - 150, 400, 140)
	surface.SetDrawColor(PBackGround)
	surface.DrawTexturedRect( x - 880 - 2, y - 150 - 2, 400 + 4, 20 + 4) 
blah blah blah 
end 
end)
  

I tried different if statements using many different booleans, checking to see if KEY was released.(in Avatar function) I couldn’t find one that worked so that’s why it’s currently bare.

Nononononononononono.
That’s wrong.
VERY WRONG.
You’re creating the avatar image vgui element every paint.
DO NOT DO THAT. THAT WILL FUCK UP YOUR FPS.
You can make it a local variable outside of the function and check if it’s valid, if it’s not re-create it and if it is valid do nothing, and make something like this but in the key press if in an else statement to remove the vgui element if it is valid.

Right, that’s what I figured, maybe the issue is just I had Avatar() in HUD paint. I’ll mess around with it when I get home.

I came up with this


local avatar
function HUDValidCheck()

    if input.IsKeyDown(KEY) and IsValid( LocalPlayer() ) && !IsValid( avatar ) then
    
        avatar = vgui.Create( "AvatarImage" )
    
        avatar:SetSize( 32, 32 )
        avatar:SetPos( 90, ScrH() - 134 )
        avatar:SetPlayer( LocalPlayer(), 32 )
    elseif IsValid( avatar ) then
		avatar:Remove()
    end
end

It works, but the only issue now is that when ever the player is holding KEY down, the avatar is practically flashing.

[editline]14th April 2016[/editline]

I think I might’ve come up with a solution lemme test it.

[editline]14th April 2016[/editline]

Yep, fixed it.

[editline]14th April 2016[/editline]

Yep, fixed it.

elseif IsValid( avatar ) and (input.IsKeyDown(KEY) == false) then
avatar:Remove()