How can I stop a line of code being ran before the player is even added?

I have a problem with spawn() since the code always runs before the player is even added (the script is a script). PlayerAdded does not work because if ex: 1 player joins, the spawn() runs, then another joins then the function is called again, which means that is gets reset.
code foundation:

function example()
--code here
end
spawn(example)

task.spawn does not work either. PlayerAdded is definetly not a good solution since the function will reset once another player joins.
faulty code:

function example()
--code here
end
game.Players.PlayerAdded:Connect(function()
spawn(example)
end)

playing the game in studio works fine but playing it in the roblox player will break it because the code already ran before the player even is added.

1 Like

I’m confused, are you saying this line is being ran before the player is added?

1 Like

Yes. The spawn() runs before the player is even added

example:
Player A joins the game. There is a little delay.
Player A’s player loads into the game. The function already ran, even though its not supposed to run without at least 1 player already in the server. (the script is a script in serverscriptservice)

Im still a new programmer xd

1 Like

And this is your code?

If so, that’s not possible the spawn line should run when the player is added.

1 Like

Just do PlayerAdded:Wait().

Code:

local function example()
	--code here
end

game:GetService("Players").PlayerAdded:Wait()
example()
3 Likes

Is that the pretty much the same thing as PlayerAdded because if I do that then if players load into the game, the function will keep on resetting

1 Like

No, it waits for the first .PlayerAdded to be fired, then goes past. Search up :Wait() and you will find out what it does.

2 Likes