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