I’m making a survival game, and I want to know if there is a way to use GetChildren() and math.random to select a random number of children inside of a folder. If not, can you show me an api article to where I can?
local obj = yourobj:GetChildren()
local Rand = math.random(1, #obj)
print(Rand)
3 Likes
heres a code snippet that should do it! i havent tested it so it might have a typo or 2
local function getRandomChildren(folder)
local children = folder:GetChildren()
local num = math.random(1, #children) -- choose a random number of children
local selected = {} -- children that will be selected
for i = 1, num do -- loop from 1 to num
local index = math.random(1, #children) -- get the index of the random child to take
table.insert(selected, children[index]) -- add that to the selected children
table.remove(children, index) -- remove that index from the children table so it wont be chosen again
end
return selected
end
2 Likes
Thanks, I’ll edit this script and I’ll try it out. I’ll let you guys know if I have an error or something.
1 Like
Im not fully understanding your question but here is what I think you want.
A random number of random children to be selected from a folder and put in a table.
To accomplish this it should look something like this:
local folder = workspace.folder -- your folder here
local total = math.random(0, #folder:GetChildren())
local children = {}
for i=0,total,1 do
local randChild = folder:GetChildren()[math.random(1, #folder:GetChildren())]
local pass = true
for i,v in pairs(children) do
if v == randChild then
pass = false
end
end
if pass then
table.insert(children, randChild)
else
i -= 1
end
end
thisis kind of a brute force approach, but it still should get the job done
3 Likes
I’d probably shuffle the table first and then select a random number of elements to create a new table out of. Here’s an implementation in Lua:
local function shuffle(t)
for i = #t, 2, -1 do
local j = math.random(i)
t[i], t[j] = t[j], t[i]
end
return t
end
local function getRandomSelection(t)
return table.pack(table.unpack(shuffle(t), 1, math.random(1, #t)))
end
local selected = getRandomSelection(folder:GetChildren())