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

end

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

48 Likes

First create an array of all the object’s children with Instance:GetChildren(), then generate a random index in the range of the amount of children and retrieve the object at that index.

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

It worked, Thanks for the help!

5 Likes

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.

36 Likes

what

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.

23 Likes

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

3 Likes

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

2 Likes

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

2 Likes

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

3 Likes

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).
Capture

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