So here’s the deal, I’m currently working on a GUI and I’m firing a client event when a player steps on a part in work space. At first I used FireAllClients() I very soon figured that it pops up the GUI on everyone’s screen. Is there anyway where I can make it where any player can step on the part and make it where the GUI pops only on the players screen who stepped on the part? Thanks. Below is the previous code.
GuiPop = game.ReplicatedStorage:WaitForChild(“GuiPopUp”) workspace.TestPad.Touched:connect(function(hit) If hit.Parent:FindFirstChild(“Humanoid”) then GuiPop:FireAllClients() End End)
Well for this purpose, you can use a handy function of the Players service called GetPlayerFromCharacter()
.
This function, like this name suggests, it returns a player object when given a character value. This can be used as the first argument of the FireClient()
function of the remote event.
Another thing to note is that lua is case sensitive, meaning that something like end
has a different meaning than something like End
, eNd
, or END
. It should always be clear that capitalization in the correct places matter, for example: if you tried to write an if statement like:
If x Then... end
It would error and neither If
nor Then
are written correctly, however, if I did
if x then ... end
it wouldn't error as if
and then
are correctly formatted keyword
With that said, the following can be done:
local GuiPop = game.ReplicatedStorage:WaitForChild(“GuiPopUp”) workspace.TestPad.Touched:Connect(function(hit) local plr = game.Players:GetPlayerFromCharacter(hit.Parent) if plr then GuiPop:FireClient(plr) end end)
Now, there is a slight problem with the code above,that being that it fires multiple times, as a character has multiple bodyparts can could be colliding with the part within a fraction of a second. That number being from 6 for R6 characters to 16 for R15 character.
An easy way to avert this would be to use a debounce.
Ex:
local GuiPop = game.ReplicatedStorage:WaitForChild(“GuiPopUp”) local PoppedPlayers = {} workspace.TestPad.Touched:Connect(function(hit) local plr = game.Players:GetPlayerFromCharacter(hit.Parent) if plr and not PoppedPlayers[plr] then GuiPop:FireClient(plr) PoppedPlayers[plr] = true--or some other truthy value wait(1) PoppedPlayers[plr] = nil end end)
Hopefully this helped you out!