How many times do you put "PlayerAdded:Connect" in your game? Once, or Many?

Should this be in a game only once as best practice?

Or should you put it in many scripts (once for loading inventory, once for playing intro song, once for updating gui with user data…)?

Does it matter if there is 50 “PlayerAdded:Connect”? Should I try to keep this low?

2 Likes

Well, you’d generally be able to script everything you needed in one PlayerAdded:Connect() since PlayerAdded runs when a player joins the game, which is once, so theres really no reason to use it repeatedly.

1 Like

Not really problematic. You should try to consolidate common functionality into reusable scripts or modules.

Only really need the one reference per server script

local Players = game:GetService("Players")
game.Players.PlayerAdded:Connect(function(player) -- player has entered the game
	player.CharacterAdded:Connect(function() -- player has (re)-spawned
	end)
end)
1 Like

I use it only once. But since I’m using Parallel LUA, part of it runs a loop to send a message to all actors in ServerScriptService that the main script knows about so each Actor (Package/Module) does what it needs to with it, in parallel.

local playerService = game:GetService("Players")

-- Called when a player logs into the server.
local function playerAdded(player)
	-- Perform some preliminary tasks.

	-- Send message to all known packages.
	for _, package in pairs(packageList) do
		if package.enabled == true then
			package.actor:SendMessage("PlayerAdded", player)
		end
	end
end

-- Called when the player's character spawns in game.
local function characterAdded(player, char)
	-- Perform some preliminary tasks.

	-- Send message to all known packages.
	for _, package in pairs(packageList) do
		if package.enabled == true then
			package.actor:SendMessage("CharacterAdded", player, char)
		end
	end
end

playerService.PlayerAdded:Connect(function(player)
	task.spawn(function()
		playerAdded(player)
	end)
	player.CharacterAdded:Connect(function(character)
		characterAdded(player, character)
	end)
end)

The above code is a basic outline of what I do.

1 Like