I am trying to print out the name of the value that has been selected by math.random(), I have a folder inside ReplicatedStorage which holds all the available power-ups, the error that I am receiving is:
Workspace.CoreScript:68: attempt to index number with 'Name'
The script:
1 | local powerUps = game.ReplicatedStorage.PowerUps:GetChildren() |
2 |
3 | local ranPowerUp = math.random( 1 , #powerUps) |
4 |
5 | if ranPowerUp.Name = = "Speed" then |
6 | print ( "Speed power-up has been selected!" ) |
7 | end |
This is a common misconception with math.random(). It does NOT pass you back the object itself, it gives you as the name implies a random number. Instead we index the table using the random number, giving us that object.
1 | local powerUps = game.ReplicatedStorage.PowerUps:GetChildren() |
2 |
3 | local ranPowerUp = math.random( 1 , #powerUps) |
4 |
5 | if powerUps [ ranPowerUp ] .Name = = "Speed" then |
6 | print ( "Speed power-up has been selected!" ) |
7 | end |
EDIT: I also heavily recommend some randomness being added. Below will set a 'randomseed' based on the time, and proc a few randoms to better 'randomize' then number given. Its always a good idea.
1 | math.randomseed(os.time()) |
2 | math.random();math.random();math.random(); |
ranPowerUp
is a number, not a userdata value. You're assuming it's a userdata value, which it evidently isn't. You can index powerUps
with ranPowerUp
in a fashion such as powerUps[ranPowerUp]
, which should give you a userdata value from the table returned by GetChildren()
. (Did you forget how GetChildren()
works?)