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 make a GUI disabled after clicking away?

Ok so, I use a ClickDetector on a part that enables and disables a GUI when clicked, but I would like it to be disabled when clicking away from the ClickDetector instead. There is my code:

local ClickD = script.Parent

function onClick(plr)
local GUI = plr.PlayerGui:WaitForChild('Loadout')
	if GUI.Enabled == false then 
		GUI.Enabled = true
	else if GUI.Enabled == true then
		GUI.Enabled = false
		end	
	end	
end

ClickD.MouseClick:Connect(onClick)

Any help is appreciated, because I couldn't figure this out. I'm also new to coding and I am willing to learn new things.

2 answers

✓ Accepted answer

ANSWER: You just have to add an event to the Mouse that detects what the player is clicking on. If it is not the ClickDetector then turn off the gui.

Note: This script will be a LocalScript in StarterPlayerScripts (Because we can't use the mouse unless it is done locally)

Code:

local LocalPlayer = game:GetService("Players").LocalPlayer
local myMouse = LocalPlayer:GetMouse()

local ClickD = workspace:WaitForChild("Part"):WaitForChild("ClickDetector") -- Be sure to properly set the path to the ClickDetector in your workspace

local GUI = LocalPlayer.PlayerGui:WaitForChild('Loadout') -- Defining this inside the function is redundant

ClickD.MouseClick:Connect(function() -- This is still your code just cleaned up
	GUI.Enabled = not GUI.Enabled
end)

myMouse.Button1Down:Connect(function() -- Here we add an event that closes the gui when clicking anywhere that is not on the ClickDetector
	if myMouse.Target ~= ClickD.Parent then
		GUI.Enabled = false
	end
end)

Note: If you're going to copy my code please remember to click "View Source" so as to copy its format correctly (And remember to remove your script when testing this out)

2 comments

0

Thank you very much!

0

Cheers!

(just read the proper answer, it's way better)

After some time, I figured out a cheap alternative. Place another clickdetector on the Baseplate (for example) and reference it in the script. Low effort but works, even better if you replace the cursor icon to the default one so it's not noticeable.

My new code:

local ClickD = script.Parent
local workspaceClickD = workspace.Course.PlacingStuff.Baseplate.ClickDetector

function onClick(plr)
local GUI = plr.PlayerGui:WaitForChild('Loadout')
	if GUI.Enabled == false then 
		GUI.Enabled = true
	else if GUI.Enabled == true then
		GUI.Enabled = false
		end	
	end	
end

ClickD.MouseClick:Connect(onClick)

workspaceClickD.MouseClick:Connect(function(plr)
	local GUI = plr.PlayerGui:WaitForChild('Loadout')
	if GUI.Enabled == true then
		GUI.Enabled = false
	end
end)

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