|
|
|
|
Reply From: |
Zylann |
My game has dozens of levels and that problem quickly appeared.
At first I had the name of the next level inside the end portal of each level. That worked, but at some point it became hard to have a big picture, and it forced to open the levels to see that order. Not nice if you want to generate the level map in the main menu.
So I thought I would give them a name with a number at the end, and keep it in a variable. So for example if I play level42.tscn
, I know I can extract the 42
using name.to_int()
and load level43.tscn
by doing str("level", num + 1, ".tscn")
.
This worked for a while, until I started shuffling the order. Renaming levels wasn’t nice, and I started getting lost in remembering which levels contained what, because they were all numbers, not very descriptive…
So I changed my approach and went for an array, written inside a script file:
# level_list.gd
const _order = [
# World 1
"level0_tuto",
"level0_tuto2",
"level1",
"level2",
"level3",
# World 2
...
]
static func get_level(var index: int):
return load(str("res://levels/", _order[index], ".tscn"))
It is technically the same as a config file, except it’s straight GDScript without the need to parse or anything like that. I can also use a function to make access cleaner. I find it more convenient than editing inside the Godot inspector as well, which is lacking in re-ordering functions etc.
Then I can access it easily anywhere, because it’s just constant data:
# In some script of the game
const LevelList = preload("res://level_list.gd")
func some_function():
var next_level = LevelList.get_level(current_level + 1)
...
Using preload
is just a convention of mine. You can make the list available globally using class_name
, or using the script into an autoload node.
What would be the best way to current_level
? By using get_level
and passing the current_scene filename to it to grab the index?
elvisish | 2021-07-29 23:47