Loading scripts in a loop

Godot Version

3.6

Question

I have a game with dozens of maps and I’d like to make more.
Each map is stored in a large gd file with information about what is on each grid, and settings.

For example in the directory “Maps/Map1/data.gd” I have:

var settings = {
“map_name”:“Map1”
“difficulty”:“easy”,
“player”:{
“name”:“player1”,
“color”:“red”
},

“map_type”: 1
}
var matrix = {
“0,0”: “empty”,
“0,1”: “enemy base”,

“999,999”:“empty”
}

I am trying to loop through these files and create a menu where you can select which map you want to play.

The problem is that godot doesn’t let you have static variables. It doesn’t let you preload scripts dynamically. So it seems I can’t simply make a loop like:

for folder in directory:
    script = load("res://Maps/"+folder+"/settings.gd")
    var data = script.get_settings()
    show_map_button(data)

How should I go about doing this without making a singleton for every map?
I could load json files from “user://”, but as this is an online game, that would require the user to enable third party cookies… and they would be some big cookies at that.

What’s the proper “godot way” of doing this?

Use custom resources for data containers.

It does actually. Using a custom resource is still the best option but for static variable you can just use (example):

class_name MyClass extends Node3d

static var my_variable

Then you can easily reference it in another script by using MyClass.my_variable.

Or just make it easy on yourself and use a custom resource. Make a script and add:

extends Resource

class_name MyResourceClass

@export var map_name : String
@export var difficulty : String
@export var player_name : String
@export color : String

Now you can right click in the file system and select “Create New/Resource” and then select “MyResourceClass” as the type. Then you can double click on the newly created resource file and in the Inspector you can fill out the information.

And that’s it. Now you can reference MyResourceClass by simply adding:

@export var my_resource_class : MyResourceClass

In the inspector drag the applicable resource file into the field just created and you’re all set. In your map script you can now simply use my_resource_class.map_name or whatever field’s information you need.