So basically I am trying to get the number of players with a value in their backpacks called Racing set to true. I know its easy, but the problem is, I'm making a racing game in which the race is supposed to end when everyone finishes, and I do that using a script that sets a value in workspace called PlayersRacing to the amount of racing players that are in the game. The problem is, I can't change the value when someone leaves during the race. (I tried PlayerRemoving, but that doesn't work) So I thought I could make a loop script that makes the PlayersRacing value the current number of players racing that are in the game, but I don't know how.
Is there a way to get a number of players with a value in their backpacks?
1 answer
In first place, setting a value within their backpacks isn't a good idea. If it's a simple game, you can simply put the value in the player. Insert the BoolValue in StarterPlayer and it will be copied to every player instance when it is created.
You can make a while loop to check something like
function CheckRacers()
local PlayersRacing = workspace.PlayersRacing
PlayersRacing.Value = 0
for i,v in pairs (game.Players:GetPlayers()) do
if v.Racing.Value then
PlayersRacing.Value = PlayersRacing.Value + 1
end
if PlayersRacing.Value == 0 then RaceFinished() end --Basically, if nobody had Racing value true, that means that the function should trigger the race end.
end
end
EDIT:
function RaceFinished()
--Do whatever has to be done once the race finishes.
end
function CheckRacers()
local PlayersRacing = workspace.PlayersRacing
PlayersRacing.Value = 0
for i,v in pairs (game.Players:GetPlayers()) do
if v.Racing.Value then
PlayersRacing.Value = PlayersRacing.Value + 1
end
end
if PlayersRacing.Value == 0 then RaceFinished() end --Basically, if nobody had Racing value true, that means that the function should trigger the race end.
end
6 comments
Use GetPlayers instead of GetChildren.
That works too.
use :GetPlayers() with :GetChildren() you can get another object insted of player.
I doubt he's placing anything else in players, but yes, :GetPlayers() is the cleaner way. I'll use it myself too, thanks.
I know I could get it that way, but how do I actually set the value to the number of racers?
Check the edited part. It isn't the best way to do it, but I guess that's the best I can do with what I know about your game and the idea I gave you in first place. It's not the smoothest way but it should work just fine. You can make an invisible block at the end of the track that changes the player's Racing value and triggers CheckRacers()
This discussion is preserved as it was. New answers, comments, and votes are closed.

1 comment
I don't think the backpack would be a proper place for a BoolValue object. Why not store it in the player instance itself?