Loop not working

Ok so I made a script that adds 1 every 1 second
I get no errors, Here’s the script:

--This is a Script put inside of ServerScriptService
local secs = game.ReplicatedStorage:WaitForChild("Seconds") --It's a int value inside of the Replicated storage.

game.Players.PlayerAdded:Connect(function(plr)
	while true do
		wait(10)
		secs = secs +1
		print(secs .." Seconds have passed.")
	end
end)

I get nothing in the output.

1 Like

Because you are redefining your secs variable. If you want to change an int value then change the .Value property of it.

task.wait is preferred over wait
using the compound addition-assignment operation a += b is shorter and equivalent to the non compound version a = a + b.

--This is a Script put inside of ServerScriptService
local secs = game.ReplicatedStorage:WaitForChild("Seconds") --It's a int value inside of the Replicated storage.

game.Players.PlayerAdded:Connect(function(plr)
	while true do
		task.wait(1)
		secs.Value += 1
		print(secs .." Seconds have passed.")
	end
end)
1 Like

The above is the solution, but as a side note, your while loop is within your Player Added event.

This means, every time a new player joins the game, another loop is created.

So instead of one second being added, the number of players who join will be added.

Move your while loop outside of the Player added event to resolve this.

local storage = game:GetService("ReplicatedStorage")
local players = game:GetService("Players")
local secs = storage:WaitForChild("Seconds")

task.spawn(function()
	while task.wait(1) do
		secs.Value += 1 --change the value of the intvalue instance
	end
end)

players.PlayerAdded:Connect(function(player)
	print(player.Name.." joined the server "..secs.Value.." from the server starting.")
end)

players.PlayerRemoving:Connect(function(player)
	print(player.Name.." left the server "..secs.Value.." from the server starting.")
end)

This while loop will also execute each time a new player is added which means after 2 or more players join the seconds counter will no longer be accurate.