Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I make a script that picks a random model in a folder?

I am working on a tower defense project, and I cannot come up with an effective script that picks a random model inside a folder.

Example: a folder has 3 models named "NormalZombie", "SpeedyZombie" and "SlowZombie" and I want the script to take one of them randomly everytime a function is fired.

Any help?

3 answers

✓ Accepted answer

To pick things randomly, I usually use the math.random function which picks the number within range : `math.random(--[[Smallest Num--]],--[[Largest Num--]].

In your case, you want to pick things within your zombie folder so you would do

local folder = --[[Your folder that contains zombie--]]
local pickedZombie = math.random(1,#folder:GetChildren()--[[putting "#" will  gets the amount of child in your table.--]])

Then you would want to create a clone for that object. You can get the thing inside your folder using table[pickedZombie]. By the way, GetChildren() returns a table of children of that folder.

local cloneZombie = folder:GetChildren()[pickedZombie]:Clone()

Last, you would want to set the parent of cloneZombie to workspace and you will soon be spawning armies of random zombies!

This is all I could think of sorry if its doesn't work as well as you want it to, I'm fairly new to scripting

local table = {~,~,~,~} -- your table, ~ can be anything, it is basically the contents of your table

while true do
	
for i, v in pairs(table)--[[the tables name, if it were a model named car, find it by typing : game.Workspace.car into the parentheses]] do
	local generator = (math.random(1,4))--[[make it so it counts from 1 to how ever many items your 
table has]]
	print(table[generator])-- do what ever you want to the items
	wait(1)
	end
end

Hope it helps

2 comments

0

Don`t forget to use the wait() in while loop or the game will crash

0

theres no need for a wait in the while loop, since it revolves around the for loop which already has a wait.

First, put all of the models in a table:

local table = {}
for i, v in pairs(folder) do
	table[i] = v
end

Then, run through a loop to pick what item from the table you want:

local number = math.random(1, #table)

You can then find the randomly generated zombie by using table[number]

This discussion is preserved as it was. New answers, comments, and votes are closed.