Spawning won't work

So, I have a survival game, and nothing is working regarding to the player.CharacterAdded event firing, i’m confused. Nothing works, not even the message printing in the function for characteradded. No errors are displayed.

players.PlayerAdded:Connect(function(plr)
	local plrData
	local isMod = modData:GetAsync(plr.UserId)
	if banData:GetAsync(plr.UserId) then plr:Kick(banData[2] or "Exploiting or teaming/assisting an exploiter is not tolerated") return end
	if isMod then
		--remoteHandler:InvokeClient(plr, "mod")
	end
	print("ismod = yes")
	local hasErrorData = errorData:GetAsync(plr.UserId) or false
	local success,err = pcall(function()
		if hasErrorData then
			plrData = hasErrorData
			else
	       plrData = data:GetAsync(plr) or DefaultData
	    end
	end)
	if hasErrorData and success then
		errorData:RemoveAsync(plr.UserId)
	end
	if not success then
		plr:Kick("Error retrieving data")
	end
	print("datacheck")
	if plrData == DefaultData then
		table.insert(plrData.inventory["bag"], {name = "Log", quantity = 2})
		_G.sessionData[plr.UserId] = plrData
		_G.sessionData[plr.UserId].serverData.hasSpawned = false
	else
		--functionBank.setPlayerInCustomizationMenu(plr)
	end
	print("charcheck")
	spawn(function()
		wait(1)
		local c = workspace:WaitForChild(plr.Name)
		_G.sessionData[plr.UserId].serverData.hasSpawned = false;
		c.HumanoidRootPart.Anchored = true;
		c.Humanoid.Health = math.huge;
		c.Humanoid.MaxHealth = math.huge;
		c:SetPrimaryPartCFrame(charCFrame)
		remoteHandler:InvokeClient(plr, "spawnplayer", spawnCFrame)
		
	end)```

Actually does work, my apologies

This could have been that the player was added before the PlayerAdded and CharacterAdded event was connected, and I sometimes have this issue when testing in studio;

In the future, it’s a good idea to structure the code like this to avoid this issue as this will catch all players in all cases:

local function characterAdded(char) -- character added!
    -- run code where the character is added here
end

local function playerAdded(player) -- player added!
    if player.Character then-- just incase the character is already in the game
        characterAdded(player.Character) 
    end
    player.CharacterAdded:Connect(function(newChar) -- run the character func on future characters when they are added
        characterAdded(newCharacter)
    end)

    -- run code for players added here
end

game.Players.PlayerAdded:Connect(playerAdded) -- connect the function to new players

for _,oldPlr in next, game.Players:GetPlayers() do -- if any player already joined then run the function on them, too
    playerAdded(oldPlr)
end

written on mobile so may be some issues, sorry!

1 Like