I'm making a game where two players race eachother to be the first to complete an obby. And I need to transmit the chosen player's names to a local script so I can show who's racing who. Here's what I have so far:
local plrs = Players:GetChildren() local n = math.random(1, #plrs) game.ReplicatedStorage.StringValues.Player1.Value = n.Name local n2 = math.random(1, #plrs) game.ReplicatedStorage.StringValues.Player2.Value = n2.Name
You're just picking up a random number, not the value from the table. You'd need to use plrs[n]
So, the code you have would essentially do this:
local plrs = Players:GetChildren() -- consider changing to Players:GetPlayers() local n = math.random(1, #plrs) -- n = random number between 1 and the no. players game.ReplicatedStorage.StringValues.Player1.Value = n.Name local n2 = math.random(1, #plrs) -- n2 = random number between 1 and the no. players game.ReplicatedStorage.StringValues.Player2.Value = n2.Name
Therefore you're trying to say for example 3.Name
, which of course doesn't make sense. If you want to get the actual player object, you need to index the table plrs
using the nth value you got from before.
As so:
local plrs = Players:GetPlayers() local n = math.random(1, #plrs) game.ReplicatedStorage.StringValues.Player1.Value = plrs[n].Name local n2 = math.random(1, #plrs) game.ReplicatedStorage.StringValues.Player2.Value = plrs[n].Name
However my final solution is simple. First principle of programming: DRY
Don't
Repeat
Yourself
And using that rule, we can use a simple for loop to make this more elegant and easier to adjust should we want to add more players to StringValues.
local plrs = Players:GetChildren() local numPlayers = 2 for i = 1, numPlayers do local n = math.random(1, #plrs) local val = game.ReplicatedStorage.StringValues:FindFirstChild(string.format("Player%d",n)) val.Value = plrs[n].Name end
I hope this helps and answers your question, if it did, please make sure to accept it :)