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

Infinite Yield Possible. How to fix this?

Currently, I am making a GUI that will open when touching a part. It works the first time you click it but doesn't after that. What should I do?

Sorry the code is really simple, I am pretty new to scripting

function onClicked(PlayerWhoClicked)
wait (0.01) --Was supposed to help the problem
PlayerWhoClicked:WaitForChild("PlayerGui").ScreenGui.FrameA.Visible = true
end

script.Parent.ClickDetector.MouseClick:Connect(onClicked)

1 answer

You should use RemoteEvents for this, because the server won't be able to directly access PlayerGui.

Make sure to have a RemoteEvent in ReplicatedStorage.

ServerScript:

local RemoteEvent = game:GetService('ReplicatedStorage'):WaitForChild('RemoteEvent')
--game:GetService('ReplicatedStorage') is another way of saying game.ReplicatedStorage

local ClickDetector = script.Parent:WaitForChild('ClickDetector')

ClickDetector.MouseClick:Connect(function(plr)
	RemoteEvent:FireClient(plr)
	--The remote event will only communicate with the player who clicked. If you want it to communicate with everyone, you can use ":FireAllClients()" without anything between the parenthesis.
end)

You can put the LocalScript anywhere in StarterGui, just make sure it can access the Frame you're trying to interact with. In this case, i'll have the LocalScript as a child of the frame so it's easier.

LocalScript:

local RemoteEvent = game:GetService('ReplicatedStorage'):WaitForChild('RemoteEvent')

local Frame = script.Parent

local Enabled = false
--this will make it open or close after each event
RemoteEvent.OnClientEvent:Connect(function()
	if Enabled == false then
		Enabled = true
		Frame.Visible = true
	elseif Enabled == true then
		Enabled = false
		Frame.Visible = false
	end
end)

This is very basic use of RemoteEvents, but you can do much more with it. If there are any problems with the scripts, please let me know.

If you want a better explanation, here are some links to the developer forum: https://developer.roblox.com/en-us/api-reference/class/RemoteEvent https://developer.roblox.com/en-us/articles/Remote-Functions-and-Events

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