Coroutine not running for both players in PlayerAdded & PlayerRemoving functions

I’m making a script to detect when 2 players join a game, and when this happens, a GUI frame will change text. However, it doesn’t seem to happen to all players in the for i,v loop.

local function playerAdded(player)
	for i,v in ipairs(game.Players:GetChildren()) do
		player = v
		coroutine.wrap(Tell)(player)
	end
end

local function playerRemoved(player)
	for i,v in ipairs(game.Players:GetChildren()) do
		player = v
		coroutine.wrap(Tell)(player)
	end
end

function Tell(player)
	local Players = game.Players:GetChildren()
	print(#Players)
	if #Players >= 2 then
		print("Hi")
		game.StarterGui.ScreenGui.Frame.TextLabel.Text = "Ready to play!"
	end
	if #Players < 2 then
		game.StarterGui.ScreenGui.Frame.TextLabel.Text = "Not enough players!"
	end
end

game.Players.PlayerAdded:Connect(playerAdded)
game.Players.PlayerRemoving:Connect(playerRemoved)

What’s interesting is in the output, the message “Hi” that I want it to print does print twice, which means it does acknowledge that it needs to run twice for both players, but the text doesn’t react that way. Anyone know why?

More context if anyone needs it

Need bind to close if u do corutine.wrap

Ok,u this silly person,

All of your functions are local,but the main function is only function???(change that to local function)

Also,this is a server script,it will only run once

I put that to nonlocal because the other functions would not recognize it. Also, your last statement, then how come the main nonlocal function ran numerous times?

I know your problem,text by right should be put it in client ,i do not know why put it in server

So I did a few things to test this theory.

  1. I changed the RunContext of the script to Client. Did not work in any classes.
  2. Made a whole new local script and put it in StarterPlayerScripts. It made the same problem, only 1 person would update.

I don’t think its the side of which the code is running, but instead what is inside of it.

Since you’re already iterating the players.

Just edit each player’s textlabel.

function Tell(player)
	local Players = game.Players:GetChildren()
	print(#Players)
	
	local textLabel = player:WaitForChild('PlayerGui'):WaitForChild('ScreenGui').Frame.TextLabel
	if #Players >= 2 then
		print("Hi")
		textLabel.Text = "Ready to play!"
	else
		textLabel.Text = "Not enough players!"
	end
end

Almost forgot I was running through the players almost mindlessly before the coroutine lol. Anyways, thanks for the solution!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.