I'm currently in the process of rewriting an old stage selection script I made. The code is extremely messy, making it hard to implement new stages and features, so I would like to use this opportunity to increase my limited knowledge of tables.
So say that the stages are located in game.ServerStorage.Maps and its children are called Map1, Map 2 and so on. How would I create a table that I could easily identify these stages in an efficient way?
Great question. What you need to identify all children, is the generic for loop. It goes through the target's children, and in this case, we'll add its name to a table!
local MapTable = {} local Maps = game.ServerStorage.Maps for i,v in pairs(Maps:GetChildren()) do table.insert(Maps, v.Name) -- you may want to double check this. I'm not at home, so no studio for me. end
The best way I can think of is creating the table by using :GetChildren()
Using your info:
local maps = game.ServerStorage.Maps:GetChildren() --Creating the table of maps --Maps are usually chosen at random, so I will provide a simple method of how to do so. local rand = math.random(#maps) --Creates a random number with the number of maps as the range print (maps[rand].Name) --Should print the name of the map its chosen
Let me know if you have any questions!
If you don't know, you can put objects, parts and even functions in tables. Use:GetChildren() to get all the maps and put all your maps in a folder or model, :GetChildren() is a better way than making a custom table because you can put alot of maps without having to keep on adding to the table.
You can make a script like this :
local mapHolder = serverStorage:WaitForChild('Maps') local maps = mapHolder:GetChildren() local randomMap = math.Random(1, #maps) -- This is a better way than making a custom table because you can have an infinite amount of maps without having to change a table. print(maps[randomMap].name) -- You can do whatever you wan't here, this just prints the chosen map name.