Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
2

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

Asked by 4 years ago

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

Log in to vote
1
Answered by
Yuuwa0519 197
4 years ago

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!

Ad
Log in to vote
0
Answered by 4 years ago

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

0
Don`t forget to use the wait() in while loop or the game will crash Yuuwa0519 197 — 4y
0
theres no need for a wait in the while loop, since it revolves around the for loop which already has a wait. XURN2950 0 — 4y
Log in to vote
0
Answered by
Joshument 110
4 years ago

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]

Answer this question