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

How to do player detection?

In one of my scripts, I realized that I was waiting for a guy NAMED player.

local w = game.workspace:WaitForChild("Player")

How do you detect a player even if his name is not named player?

1 comment

0

i dont really know but i would try to use a different thing like the player added event

2 answers

✓ Accepted answer

An easy way to detect if a player has join the game is to use the player added event.

game.Players.PlayerAdded:connect(function (player)
	
end)

How do I detect if a player has joined?

It completely depends on whether you are using a server side script or a local client side script. Both ways work differently.

So how would I do it in a local script?

You would want to hook up a repeat loop to check if game.Players.LocalPlayer is nil or true.

local players = game:GetService("Players") --This is optional, I just prefer having my services in a variable
repeat wait() until players.LocalPlayer --or until game.Players.LocalPlayer
local player = players.LocalPlayer
--Put your code below

How would I do it with a server side script?

You can use the playeradded event and call it to all the current players as well. Do this at the beginning of your script, or you may glitch your game out.

local Players = game:GetService("Players")
 
function playerJoined(player) --This is necessary, and you can change the code inside to whatever you need.
     print(player.Name .. " has entered the game")
end
 
Players.PlayerAdded:connect(onPlayerAdded)

for _,player in pairs(Players:GetPlayers()) do --This for loop looks and does whatever needs to be done to everyone in the game.
     onPlayerAdded(player)
end

Both of these methods work, but they only work in their respective scripts.

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