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

How do I make a variable representing a random object?

Asked by
tber8 37
7 years ago

What I want to know is how to get a randomized object and make a variable represent it.

If you are thinking about reporting me, here is me failing at trying.

map = game.ReplicatedStorage.Maps.Random

1 answer

Log in to vote
2
Answered by 7 years ago
Edited 7 years ago

What are you trying to do? Do you have a list of objects in there, and you wanna pull a random one out?

Since you didn't provide many details Ill try my best.

So lets say you have a folder in ReplicatedStorage called Maps. Inside that are a bunch of models, each being a different object. Lets pretend you have three models, each with parts and stuff inside them, and the models are named m1, m2, m3.

What you could do, is find all of game.ReplicatedStorage.Maps's children with a simple loop, and put each of its children into an table / array. http://wiki.roblox.com/index.php?title=API:Class/Instance/GetChildren

This way you could use math.random() to find a random index in the array. First we will need to set a seed, so we will type math.randomseed(os.time());and Ill put it at the top of the file. (What this does is let us get better random numbers)

Since we have a loop that puts every child in the Maps folder into a table, all we have to do is get a random number between 1 and however many entries are in that table (which we can get with table.getn(tableNameGoesHere)). So it should look like this list[math.random(1,table.getn(list))];

Now I will say I dont know if you want this to load in something for all players, or for just one, but I presume you are intending to use this server script side.

Put it all together and you have:

math.randomseed(os.time());
local list = {};
function foo()
for index, child in pairs(game.ReplicatedStorage.Maps:GetChildren()) do
        wait();
        list[index] = child;
end
local randomMap = list[math.random(1,table.getn(list))]:Clone();
randomMap.Parent = workspace;

end
foo();

TL;DR: Make a table of all the children from the parent folder that they are in, then use math.random functions to call a random index in that table and return that result.

Hope this helps.

(Btw check out these Rwiki pages:)

http://wiki.roblox.com/index.php?title=API:Class/Instance/GetChildren

http://wiki.roblox.com/index.php?title=Random_numbers

Ad

Answer this question