Picking a random object within a folder

SS = game:GetService("ServerStorage")

WeaponList = SS:WaitForChild("Weapons")

Weapons = WeaponList:GetChildren()

local MaxWeapons

for i = 1, #Weapons do

MaxWeapons = MaxWeapons + 1


local PickedItem = math.random(1, MaxWeapons)

print("Chosen Item: " .. PickedItem)

Basically, I’m trying to create a system that chooses a random item from a folder, that then places the chosen item into the map.

I’ve got the randomizer done. I just don’t know how to select the chosen object from the folder to clone into the workspace. A bit of help would be much appreciated


To do this you can get a random number from 1 to the amount of children in the object and then pull that from the folder.

local items = WeaponList:GetChildren()
local randomItem = items[math.random(1, #items)]

It worked, Thanks for the help!


On a side note, you can just set math.random(#items) as well. Because if the function only finds one value, it will automatically set it as max and default minimum as 1.



Is that behaviour even documented or did I just miss it all this time? I literally never knew you could do this before. I would always account for a case of 0 items or 1 item in a table where a random item was selected.

I can literally remove all that work and just use the length operator to set the interval automatically.

Wow, what.


Bumping this old post because for some reason this does not work anymore which is really odd.


Are you experiencing an issue of empty tables or something else?


This does still work, if you’re referencing the random table index

1 Like

For some reason it doesnt not work for me, i dont understand why, i have the exact same code.

1 Like

Instead of necroposting, you should make a new thread to ask for help and provide the code that you already wrote


hes right it dose not work anymore i have the exact same script

the exact code works perfectly for me. WeaponsList has to be a folder WITH MORE THAN 1 ITEM (sorry for caps had to make it clear)

It shouldn’t need more than one item. It should function perfectly fine using a table with only one item.

You can’t math.random 1 from 1, it throws an error for me

1 Like

This script still works with math.random(1, 1) and math.random(1).

However, it throws an error if you try math.random(1, 0) or math.random(0). If you are having this problem, then use math.random(math.max(#item, 1)). Note: It will return nil if there are no items.

yes this works, I was just an idiot and had it giving a 0 not a 1