game.Players.PlayersAdded not working

So my script is like this:

while game:GetService("ReplicatedStorage"):FindFirstChild("Time").Value ~= 0 do

wait(1)

game.ReplicatedStorage.Time.Value = game.ReplicatedStorage.Time.Value - 1

end
print("Test")
char = nil

game.Players.PlayerAdded:Connect(function(plr)

if plr then

print("ok")

end

print("worked")

repeat wait()until plr.Character

repeat wait()until char:FindFirstChild("HumanoidRootPart")

char = plr.Character

print(plr.Character)

end)

print(char)

Its not working when it hits game.Players.PlayersAdded
I tried many things and my output is Test and nil I just don’t understand the problem here

You run this after your time value reaches zero, so it will only fire for players who join the game after this point. You may want to perform any logic on existing players who were in the game during the countdown by looping through game.Players:GetPlayers() too.

As a side note, if you enclose your code in three backticks at the start and end (```) it will keep the tab spacing and format it in monospace to make it easier to read.

3 Likes

what my script does is there are enemies in a tower defense game and and i want make a collision group between them so it doesn’t matter if i do it after or before the time reaches zero the timer is just a countdown for the enemies to spawn and I can’t because the game.Players.PlayersAdded function is not working

and can you show me a example of the (```)

```This is an example of encasing your code ```
2 Likes

2 Likes

the playeradded function will start looking for players AFTER the timer loop has finished. So it will only detecct new players after that code has fully completed running

2 Likes

so do i put the player added function at the start

Instead of doing repeat loops for plr.Character and HumanoidRootPart you can do

local char = plr.CharacterAdded:Wait()
char:WaitForChild("HumanoidRootPart")
1 Like

thanks for everyone its a huge help

yes, put it at the start before the while loop

1 Like

thank you so much I fixed it
this give me so much trouble