game.Players.PlayerAdded Not Working

So after fixing infinite yield issues, I’m now faced with another issue. For some reason, whenever I insert and set up the model (via script), I keep facing the issue of one of the essential scripts’ PlayerAdded event not firing, and I’m unsure what the reason for this is. I have an auto updater script which is linked to this (I redesigned this after the last issue by the way), and I feel its something to do with the script running after the player joins. Help? I literally have no idea what the cause of this is.
Auto Updater Script

local insertService = game:GetService("InsertService")
local id = 6408603034

local function UnpackModel(Model)
	for index, Item in pairs(Model:GetChildren()) do
		Item.Parent = Model.Parent
	end
	Model:Destroy()
end
local Model
local success, errormsg = pcall(function()
	local latestVer = insertService:GetLatestAssetVersionAsync(id)
	Model = insertService:LoadAssetVersion(latestVer)
end)
if Model ~= nil then
	local NewModel = Model["J+ Admin"]
	NewModel.Parent = workspace
	NewModel.Instructions:Destroy()
	for index, item in pairs(NewModel:GetChildren()) do
		if item:IsA("Model") then
			item.Parent = game:GetService(item.Name)
			UnpackModel(item)
		end
	end
	Model:Destroy()
end
script.Parent:Destroy()

Main Handler Script (The One With The Broken PlayerAdded Event

--//Variables//--
local commandsModule =require(game.ServerStorage:WaitForChild("commands", 10))
local modModule = require(game.ServerStorage:WaitForChild("moderationDataCommands"))
local ChatLogsTable = {}
local httpService = game:GetService("HttpService")
local coolDownAmount = 360 --One request from the player 6 minutes
local textService = game:GetService("TextService")
local groupId = 7895196
local requiredRank = 253
local J_AdminBugReportWebhook =  "https://discord.com/api/webhooks/812712579008430101/VDjyQ8YRcQR874svf_PyK5ARdS47FTDF1m989Kg5fszVGP8cbKKGma2wdccLW8_FvOs0"
--//PlayerAdded Handler//--
game.Players.PlayerAdded:Connect(function(Player)
	print("Recieved Event")
	modModule.PresetData(Player)
	modModule.OverwriteData()
	print("Instanced")
	local isLoggedIn = Instance.new("BoolValue")
	local isWaiting = Instance.new("BoolValue")
	isWaiting.Name = "IsWaiting"
	isWaiting.Parent = Player
	isLoggedIn.Name = "Verified"
	isLoggedIn.Parent = Player
	print(isLoggedIn.Parent.Name)
	if modModule.CheckBan(Player) then
		print("Configured Datastores")
		local warns = Instance.new("IntValue")
		warns.Parent = Player
		warns.Name = "Warns"
		game.ReplicatedStorage.sendCommands:FireClient(Player,commandsModule)
		game.ReplicatedStorage.refreshPlayers:FireClient(Player)
		print("Fired Table And Instanced All Values!")
		Player.Chatted:Connect(function(Chat)
			table.insert(ChatLogsTable, #ChatLogsTable+1, Player.Name..": "..Chat)
		end)
	else
		Player:Kick("Sorry "..Player.Name.." But You Are Still Banned, If You Want To Be Unbanned then appeal to an admin")
	end


end)
--//Loop Saving Moderation Data//--
while wait(30) do
	modModule.SaveData()
end
--//On Server Event//--
game:GetService("ReplicatedStorage").updateLoggedInVal.OnServerEvent:Connect(function(Player, LoggedIn)
	if LoggedIn then
		Player.Verified.Value = true
		print("Set!")
	end
end)
--//Verify Player Handler//--
function VerifyAndReturn(Player)
	if Player:GetRankInGroup(groupId) >= requiredRank then
		return true
	else
		local isInModule
		for index, Id in pairs(require(game.ServerStorage.allowedIDs)) do
			if Player.UserId == Id then
				isInModule = true
			end
		end
		if not isInModule then
			return false
		else
			return
		end
		
	end
end
game:GetService("ReplicatedStorage").isVerifiedCallback.OnServerInvoke = VerifyAndReturn
--//Chat Log Returner//--
function GetAndReturnChatLogs()
	return ChatLogsTable
end
--//Moderation Handler//--
function ReturnModerationsForPlayer(Player)
	return modModule["Player-"..Player.UserId]
end
game:GetService("ReplicatedStorage").getDatastoredModerations.OnServerInvoke = ReturnModerationsForPlayer
--//Player-Removing Handler//--
game.Players.PlayerRemoving:Connect(function(Player)
	game.ReplicatedStorage.refreshPlayers:FireAllClients()
end)
--//Bug Report Manager//--
game.ReplicatedStorage.sendHTTP.OnServerEvent:Connect(function(Player, sentText)
	if not Player.IsWaiting.Value then
		local filteredString = textService:FilterStringAsync(sentText, Player.UserId)
		if filteredString then
			local resultString = filteredString:GetNonChatStringForUserAsync(Player.UserId)
			print("Player "..Player.Name.." Sent: "..resultString)
			local Data = {
				["content"] = "**J+ Admin Bug Report received!**\n\n*Username:* `"..Player.Name.."`\n*Feedback:*\n`"..resultString.."`"
			}
			Data = httpService:JSONEncode(Data)
			Player.IsWaiting.Value = true
			httpService:PostAsync(J_AdminBugReportWebhook, Data)
			wait(coolDownAmount)
			Player.IsWaiting.Value = false
		end
	end
end)
1 Like

Hi, how are you? Hope you doing well!
So the script is stopping at some point and it doesn’t get to the PlayerAdded function.
There are many things that would actually happen:

1- On the first part of your script you added a require which won’t make the script run until the required variable is found, in other words, maybe one of the first two required models didn’t load or isn’t found for some reason, so when you use require the script won’t run the code until the required variable is found. So try finding the problem there, maybe add a print after those two variables.

2- If the required variables are there so try adding a variable like the following
local player = game.Players.LocalPlayer or game:GetService(“Players”).LocalPlayer

then go make your function something like this
player.PlayerAdded:Connect(function(plr)
print(“Code got the function”)
– then keep working with your script
– hope my answer was helpful! If you have any questions I’m happy to help!

2 Likes

You could just use:

game.Players.ChildAdded:Connect(function(child)
	if child:IsA("Player") then
		
    end
end)

instead of using .PlayerAdded.

1 Like

I’m not sure if your second suggestion would work, seeing as they are both server scripts, however I’ll try your solutions

Will do! Is there an optimisation or something by doing this

Oh! Ok, I get it now, so try the thing about the first one I talked about with you.

2 Likes

This will check if players are in the game before the PlayerAdded event is connected.

local function playerAdded(player)
    
end

for _,player in pairs(players:GetPlayers()) do
    coroutine.wrap(playerAdded)(player)
end

players.PlayerAdded:Connect(playerAdded)
1 Like

It’s pretty much the same to be fair, it doesn’t really change anything.

1 Like

Your PlayerAdded is not firing because when it runs, the player has already been added.
This is most likely because of your :WaitForChild()'s above the event.

:WaitForChild() is extremely important when working on code ran by the client (in aLocalScript). Roblox does not guarantee the time or order in which objects are replicated from the server to the client. This can cause scripts to break when indexing objects that do not exist yet.
You do not need to use it in this case, since it’s a ServerScript.

Also, the dot operator is approx. ~ 20% faster than using :FindFirstChild(), if that’s what you were planning to replace it with.

Anyways, to the solution:

local Players = game:GetService('Players')


local function PlayerAdded(Player)
	-- Code.
end


local GetPlayers = Players:GetPlayers()
for i = 1, #GetPlayers do
	local Player = GetPlayers[i]
	-- Runs the following function in parallel for each player already in the server before the PlayerAdded event runs.
	coroutine.resume(coroutine.create(function()
		PlayerAdded(Player)
	end))
end
-- Hook up a connection to detect new players.
Players.PlayerAdded:Connect(PlayerAdded)
4 Likes