Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Is there a lag free alternative to running a while loop continuously?

Hi! Basically, I want a function which constantly is updating a value (more specifically, I have a value called CurrentPlayers, and I want it to be the same as the number of players in the server. Here is what I have right now:

function currentPlayers()
	while true do
		wait()
		System.CurrentPlayers.Value = #game.Players:GetChildren()
	end
end
delay(0,currentPlayers)

My question is: does this cause lag, and if so, is there a lag free alternative to achieve the same thing?

2 comments

0

What will help is use a corouine before the while true do

0

"The weird problem" is that System is a variable. Please at the top of the script add, "local System =" blah blah blah.

2 answers

✓ Accepted answer

Use NumPlayers instead of #game.Players:GetChildren(). Also, use the changed event. This event fires when a certain value changes.


NumPlayers is in game.Players.

print(game.Players.NumPlayers)

Changed event works for pretty much any value. In the parameter it also tells you what has changed.

workspace.Player1.Humanoid.Changed:connect(function(jump)
	if jump == "Jump" then
		print("Player1 has jumped.")
	end
end)

You can use this same script and edit it to make an antijump script.

workspace.Player1.Humanoid.Changed:connect(function(jump)
	if jump == "Jump" then
		workspace.Player1.Humanoid.Jump = false
	end
end)

But what are the chances a player named player1 exists? Use the player and character added events.

game.Players.PlayerAdded:connect(function(player)
	player.CharacterAdded:connect(function(character)
		character.Humanoid.Changed:connect(function(jump)
			if jump == "Jump" then
				workspace.Player1.Humanoid.Jump = false
			end
		end
	end)
end)

Now we add it together to see how many players are in the game.

game.Players.Changed:connect(function(numplayers)
	if numplayers == "NumPlayers" then
		System.CurrentPlayers.Value = game.Players.NumPlayers
	end
end)


Hope it helps!

1 comment

0

Actually, weird problem is happening. Here is the code:game.Players.Changed:connect(function (NumPlayers) System.CurrentPlayers.Value = game.Players.NumPlayers end)

This discussion is preserved as it was. New answers, comments, and votes are closed.