Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I make this If Statement print out the name of the value selected by math.random() ?

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

2 answers

✓ Accepted answer

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();

3 comments

0

Thank you, it worked!

0

math.random() will not change the internal seed; making calls will not adjust the "randomness".

0

Internally i know this, but it FEELS more random. Which makes it true.

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

This discussion is preserved as it was. New answers, comments, and votes are closed.