Ad
Log in to vote
0

"Attempt to index number with Name" - What's wrong?

Asked by 6 days ago
Edited by Ziffixture 6 days ago

Please encode Lua code in the Lua block code tag (look for the Lua icon in the editor).

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
0
Sorry about the code block not being right. I don't know how to fix it. Desmondo1 70 — 6d
0
put it in this ~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~ valk_3D 111 — 6d

2 answers

Log in to vote
1
Answered by 6 days ago

You're just picking up a random number, not the value from the table. You'd need to use plrs[n]

Ad
Log in to vote
0
Answered by 6 days ago

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 :)

Answer this question