I am working on a round-based game, there is a function that runs at the start of a round, but I’m having a little issue with it, if a player joins mid-round, then that print wont appear, it works fine for players that joined before the round, when they respawn, the print appears, for players that joined mid-round, future rounds will work fine for them, I tried to make so when the PlayerAdded event is fired, it takes the character into account, doesn’t work, though. And every time i tried to fix it, it would print twice, or more than that. Any help?
game.Players.PlayerAdded:Connect(function(player)
wait()
print(player.Name.. " Joined game")
local Connection
Connection = player.CharacterAdded:Connect(function(character)
wait()
print("Character Spawned")
end)
-- it disconnects the connection after the round, but i just hid that function for posting
end)
-- this part works just fine
for _, player in pairs(game.Players:GetPlayers()) do
if player.Character then
local Connection
Connection = player.CharacterAdded:Connect(function(character)
wait()
print("Character Spawned")
end)
--disconnection after a round
end
end
Since this is only related to the player character, you can remove all of it and just write one line of code in a script inside game.StarterPlayer.StarterCharacterScripts:
local character = script.Parent
local player = game.Players:GetPlayerFromCharacter(character)
print("Character Spawned")
If you want to add the script in ServerScriptService however, you can try the following trick:
local function characterAdded(character: Model)
print("Character Spawned")
end
local function playerAdded(player: Player)
pcall(characterAdded, player.Character or player.CharacterAdded:Wait())
player.CharacterAdded:Connect(characterAdded)
end
for _, player in pairs(game.Players:GetPlayers()) do
task.spawn(playerAdded, player)
end
game.Players.PlayerAdded:Connect(playerAdded)
That way you get rid of copying code multiple times because you can just include it once in your characterAdded and playerAdded functions.
I wouldn’t be able to do it via client, since the print was only an example, what im really trying to do is give the player a weapon (its randomized, so i cant put it in starterpack) Im going to test the server script in a second, and i will come back with results.
A script inside StarterCharacterScripts is a script that gets parented under the character every time they spawn, it runs on the server, not the client. That’s why instead of fetching the player instance through game.Players.LocalPlayer I fetch it through GetPlayerFromCharacter.
I apologize, i completely forgot that StarterCharacterScripts can have server scripts, even though i already have some server scripts in there, I did what you said (using GetPlayerFromCharacter) set up a few things, and boom, it all works now. Thank you so much for your help!