Select random item from a folder

Hello, i was working on my game and i was making a script that would select a random tool out of a Folder
Here is my code:

local folder = game.Lighting.Common
local tools = {
folder:GetChildren()
}
local choosen_tool = tools[math.random(1, #tools)]

I am sure i made a mistake somewhere, thanks for your help!

Yes, you were very close. Just take out the brackets around folder:GetChildren(). GetChildren() automatically returns a table for all of the children, so you don’t need to put that table inside of another table.

local folder = game.Lighting.Common
local tools = folder:GetChildren()

local choosen_tool = tools[math.random(1, #tools)]
2 Likes

It’s already in a table when you define the choosen_tool variable w h e e z e, just remove the table brackets

:GetChildren() returns a table by itself, so encasing it with brackets is creating a table within a table. Just remove the brackets.

I have removed the brackets and its not working


take a look at the error at the output

You got an instance from the folder. Since you are using it for a string value, you need to get the name of that instance, so just add .Name to the end of it. On Line 19 do this:

gui.Frame.Gradient.val1.Value = chosen_tool.Name

That is because you are trying to change a String value to an instance, I am unsure about your file structure and what value you are trying to get from the Instance.

The problem isnt the Gui value, its the random selection

local choosen_tool = tools[math.random(1, #tools)]

Do i need to add the Name at the :Getchildren()?

Did you try adding .Name to the end of the line? You cannot put an Instance into a string value, but you can put the Instance’s name inside.

4 Likes

Thanks alot man and everyone who helped,
I missed the name and mixed up String and Instance
Thank you!

1 Like