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:
local powerUps = game.ReplicatedStorage.PowerUps:GetChildren() local ranPowerUp = math.random(1, #powerUps) if ranPowerUp.Name == "Speed" then print("Speed power-up has been selected!") 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.
local powerUps = game.ReplicatedStorage.PowerUps:GetChildren() local ranPowerUp = math.random(1, #powerUps) if powerUps[ranPowerUp].Name == "Speed" then print("Speed power-up has been selected!") 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.
math.randomseed(os.time()) 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?)