Keyboard “F1” Toggle UI Visibility

--[[ 
    -- Script Snippet added by: togagames
    for: LuaSnippets.com and CoreGames.com
    
    Toggle a UI object's visibility by pressing the F1 key
    Instead of using an "if" statement we increment 
    _healthInvis by 1 each time and check if it's
    divisible by 2, switching between 1 and 0.
    
    This script should be in a "client" context
    and the target UI (to toggle visibility of) should be 
    added as a Custom Property of this script.
--]]

local _healthBar = script:GetCustomProperty("CanvasControlH"):WaitForObject()
local _healthInvis = 1 -- 1 if the object starts off as being "visible"

-- switch this object's visibility between 1 & 0 (on/off)
local _hSwitch = {nil}
_hSwitch[0] = Visibility.FORCE_OFF
_hSwitch[1] = Visibility.INHERIT

function OnBindingPressed(player, binding)
    if(binding == "ability_extra_50")then -- F1 key
        _healthInvis = _healthInvis + 1
        print( "Pressed: ",binding, _healthInvis%2 )
        _healthBar.visibility = _hSwitch[_healthInvis%2] -- 0 or 1
    end
end

function OnPlayerJoined(player)
    -- hook up binding in player joined event here
    player.bindingPressedEvent:Connect(OnBindingPressed)
end

-- on player joined/left functions need to be defined before calling event:Connect()
Game.playerJoinedEvent:Connect(OnPlayerJoined)

Latest Posts