Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I open AND close my GUI using one Key?

Hello,

I have been working on a game for someone and I am struggling with this part.

Basically, what I want to do is I want to open and close a gui by using :TweenPosition . I have done the opening the GUI part, but I don't know how I can close it? Or in other words, how would I close make the GUI head to a position after it has been opened already.

function onKeyPress(actionName, userInputState, inputObject)
	if userInputState == Enum.UserInputState.Begin then
		local gui = game.Players.LocalPlayer.PlayerGui.KeyBinds.Frame
		gui:TweenPosition(UDim2.new(0.382, 0,0.229, 0))
	end
end
 
game.ContextActionService:BindAction("keyPress", onKeyPress, false, Enum.KeyCode.Q)

So I have done this part and now I am unsure on how I would check if the GUI is in a certain position and then the key is pressed, the gui shoudl tween to another position For example,


if gui.Position == (0.382, 0,0.229, 0) and if the Q key is pressed
  gui:TweenPosition(UDim2.new (0.382, 0,1.229, 0))

Thats the only way I can think of on solving this issue. If there is another way, please do let me know and I am not sure about how I should come about to scripting this.

Thanks, TonyV

EDIT:

So i tried this

local gui = game.Players.LocalPlayer.PlayerGui.KeyBinds.Frame

function onKeyPress(actionName, userInputState, inputObject)
	if userInputState == Enum.UserInputState.Begin then
		gui:TweenPosition(UDim2.new(0.382, 0,0.229, 0))
		
	elseif gui.Position(0.382, 0,0.229, 0)then
		gui:TweenPosition(UDim2.new(0.382, 0,1.229, 0))
		
	end
end
 
game.ContextActionService:BindAction("keyPress", onKeyPress, false, Enum.KeyCode.Q)

but i got an error from the output saying : ContextActionService: Unexpected error while invoking callback: Trying to call method on object of type: UDim2 with incorrect arguments. I have no idea what that means, can someone help me?

1 answer

✓ Accepted answer

For this, you should use UserInputService. Also gui.Position() isn't a method and to check the position do gui.Position == UDim2.new(). Here is what code I came up with:

local UIS = game:GetService("UserInputService")
local gui = game.Players.LocalPlayer.PlayerGui.KeyBinds.Frame

UIS.InputBegan:Connect(function(Input)
	if Input.UserInputType == Enum.UserInputType.Keyboard and Input.KeyCode == Enum.KeyCode.Q then --User pressed Q
		if gui.Position == UDim2.new(0.382, 0, 0.229, 0) then --If open
			gui:TweenPosition(UDim2.new(0.382, 0, 1.229, 0)) --Close UI
		else --Is closed
			gui:TweenPosition(UDim2.new(0.382, 0, 0.229, 0)) --Open UI
		end
	end
end)

1 comment

0

oh wow. I read teh dev forums and it gave me what I put, Thanks for this!

This discussion is preserved as it was. New answers, comments, and votes are closed.