I have a simple script that sets the gun’s network owner to the player.
but I get this. You can see the script, and the first thing it’s supposed to do is print “e”, and it doesn’t print anything in the output.
From the documentation:
This event does not work as expected in solo mode, because the player is created before scripts that connect to PlayerAdded run.
One way to fix this is to create a function that you both connect to the event and call for every player that already exists. For example:
local Players = game:GetService("Players")
local function onPlayerAdded(player)
-- code
end
Players.PlayerAdded:Connect(onPlayerAdded)
for _, player in Players:GetPlayers() do
task.spawn(onPlayerAdded, player)
end
Just like @riles0829 said, it is good practice to use a function instead of binding it directly to an event. If I have a script that waits 3 seconds for example then a player can join before it is executed. You always want to declare the event “.PlayerAdded” and then loop through the current already existing players to ensure that the function runs for all players.
If the server script is inside the player or character instance, then the PlayerAdded event is getting fired first, and the script is then loading, however putting it in the ServerScriptService would make it so the script loads first, then the Player joins the game and fires that event. I suppose that’s the error, hope this helped!