Getting next item from Folder

Hello Devs!
I have problem with getting NEXT item, map, etc from Folder.

As an example we have map with 23 levels.
Levels name are “Level{Number}”.
All Levels are stored in ReplicatedStorage.
And when player go through portal, next level is loaded.

I know that we need Load and UnLoad functions.
In UnLoad function we are deleting current level from Workspace, in Load function we are getting next level and we are inserting it to Workspace.

Problem is with loading order. When we want to Load e.g. Level 1, then the Level 2 loads instead of Level 1.

Here’s a function which assigns levels to their corresponding table indexes from any numbers stored in the level’s name.

local RepStorage = game:GetService("ReplicatedStorage")
local Levels = RepStorage:WaitForChild("Levels") -- 'Levels' location

local LevelTable = {}

local function GetLevels()
	for ind, Level in pairs(Levels:GetChildren()) do
		--"%D" matches every character that's not a digit

		local TabIndex = Level.Name:gsub("%D", "")
		tonumber(TabIndex) -- We have to use tonumber here so any multi digit string gets properly converted
		LevelTable[tonumber(TabIndex)] = Level 
		-- Since it's a dictionary, we have to use tonumber here again
		-- otherwise indexes are strings

With this, you should be able to load levels by referring to the proper index.
Here’s an example with a ‘GetNext’ function:

local function GetNext(Level)
	local newKey, newLevel

	newKey, newLevel = next(LevelTable, Level)

	return newLevel

local CurrentLevel = 1
local NewLevel = GetNext(CurrentLevel)

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.