.PlayerAdded only working half the time in Studio?

So for some reason, .PlayerAdded only works half the time using the Studio play.(F5). It will take phases where it will work then it wont…

Is this regular behavior, or is it a glitch?
Note: whenever it does not work in studio, it works perfectly in the StartServer (F7) and in-game. This is a very annoying thing because I’ve spent hours troubleshooting a problem that all leads to this.

9 Likes

This doesn’t happen to me. Are you using Datastores inside of your PlayerAdded function?
If so, that may be the cause.
You should also add some prints and see if it does or doesn’t print.
If not, this may belong in studio bugs.

1 Like

Hmmm I guess an alternative is

game.Players.ChildAdded:Connect(function(plr)
 
end)

Maybe this will work better since I don’t think it’s possible to make events more accurate

2 Likes

Sometimes your server/client scripts start a bit after your client joins the game. I’ve had this happen too. I just have a function called OnEveryPlayerJoin and pass it a function as an argument. That function runs for every player that has joined the game and is currently in the game once it is bound. Have another module or script with this code in it:

local playersJoined = Players:GetPlayers()
local playerJoinCallbacks = {}
Players.PlayerAdded:Connect(function(player)
	table.insert(playersJoined, player)
	
	for _, callback in pairs(playerJoinCallbacks) do
		coroutine.wrap(callback)(player)
	end
end)

Server.OnEveryPlayerJoin = function(callback) -- Used to make sure that play solo joins are captured (or just players that join before code is ran)
	table.insert(playerJoinCallbacks, callback)
	
	for _, player in pairs(playersJoined) do
		coroutine.wrap(callback)(player)
	end
end

This way, the callback will run for every player CURRENTLY in the game and once any player joins the game.

4 Likes

If it’s still an issue, then sometimes the player will be added before the server has time to kick off the server-side scripts. This only happens when testing with play solo locally.

A way to mitigate this is to scan through players too:

function PlayerAdded(player)
end

game.Players.PlayerAdded:Connect(PlayerAdded)
for _,player in pairs(game.Players:GetPlayers()) do
   spawn(function() PlayerAdded(player) end)
end
11 Likes

Thank you everyone for your quick replies. Good to know this aint a problem with my studio. I appreciate it!

5 Likes

this is known as visitor pattern, right?