I've been learning Lua lately, most recently Derma menus.
I'm current trying to draw an image on screen when a player is in a vehicle, the functionality works, but can't see to figure how to remove/hide said icon when the player leaves the vehicle
Heres the code
function DrawIcon()
if LocalPlayer():IsPlayer() and LocalPlayer():InVehicle() and LocalPlayer():Alive() and IconOn == false then
local BeltIcon = vgui.Create("DImage")
BeltIcon:SetImage("dimBelt/seatbelt.png")
BeltIcon:SetSize(50,50)
BeltIcon:SetPos(500,500)
BeltIcon:SetVisible(true)
elseif LocalPlayer():InVehicle() == false and IconOn == true then
BeltIcon:SetVisible(false)
end
end
hook.Add("Think", "DrawIcon", DrawIcon)
and the error I'm getting
attempt to index global 'BeltIcon' (a nil value)
Please note I'm pretty new to coding so if I'm doing something dumb forgive me!
Thanks!
You define "BeltIcon" in the first if statement but you're trying to access it in the second if statement.
Lua 5.1 Reference Manual
Ahhh, that makes sense. How could I get around this?
Declare it outside of the if statement (basically right beneat 'function DrawIcon()' line) , so its in scope for both.
Reading up on scoping will clarify this for ya
Seems that got rid of the error, but unfortunately it seems to still not want to hide.
Here's what I have so far, any ideas?
local IconOn = false
local SeatbeltOn = false
function DrawIcon()
local BeltIcon = vgui.Create("DImage")
BeltIcon:SetImage("dimBelt/seatbelt.png")
BeltIcon:SetSize(50,50)
BeltIcon:SetPos(150,500)
BeltIcon:SetVisible(false)
if LocalPlayer():IsPlayer() and LocalPlayer():InVehicle() and LocalPlayer():Alive() and IconOn == false then
BeltIcon:SetVisible(true)
LocalPlayer():ChatPrint("Icon ON")
IconOn = true
elseif LocalPlayer():InVehicle() == false and IconOn == true then
BeltIcon:SetPos(200,200)
LocalPlayer():ChatPrint("Icon OFF")
IconOn = false
end
end
hook.Add("Think", "DrawIcon", DrawIcon)
That's because you are creating a vgui element every frame, you should define BeltIcon outside of the DrawIcon function. You only need to call BeltIcon:SetVisible then.
BeltIcon:SetVisible(LocalPlayer():InVehicle())
There we go! Got it working! Appreciate the help guys!
Sorry, you need to Log In to post a reply to this thread.