Factory for creating global variables?

v4.4.1.stable.official [49a5bc7b6]

Hi! I need some help in thinking about a factory design. The problem:

I have a directory with scenes. Each scene is a button for a hotbar. My hotbar is responsible for adding the buttons to itself and call their animation afterwards.
Right now, I add every scene manually in the script. I was wondering, if I can write a factory for reading the directory and looping through all files, create a variable for every scene and assign the scene to that variable.

Scoping is a problem, of course. Can Godot dynamically create variables outside a function scope?
Is this approach flawed?

extends Control

var btn_power = preload("res://scenes/buttons/btn_power.tscn")
var btn_storage = preload("res://scenes/buttons/btn_storage.tscn")
var btn_satellite = preload("res://scenes/buttons/btn_satellite.tscn")
var btn_bigpack = preload("res://scenes/buttons/btn_bigpack.tscn")


func _ready() -> void:	
	$Hotbar.add_child(btn_power.instantiate(), true)
	$Hotbar.add_child(btn_storage.instantiate(), true)
	$Hotbar.add_child(btn_satellite.instantiate(), true)
	$Hotbar.add_child(btn_bigpack.instantiate(), true)

# call add_module("btn_power") from somewhere else...

func add_module(mod_str: String) -> void:
	var mod: Node = $Hotbar.get_node(mod_str)
	if mod == null:
		print("[HOTBAR] Could not find module with name %s." % mod_str)
		return
	mod.animate_in()

I’d suggest a dictionary or an array would solve this for you.

1 Like

Gnah, right. Instead of single variables just a dictionary doing it. Thanks!

I don’t see why not.

could you elaborate on this?
what is it you are having trouble with?

from the docs, there’s this:

1 Like

I am defining the variables (i.e. var btn_power) in class scope first. If i did that in a function, the scope for all variables would decrease to function level. I can’t do that for example (pseudo gdscript):

func create_variables("some_name"):
 var some_named_thing = preload("somename"+.tsnc).instantiate()

func add_to_tree(some_named_thing):
  add_child("some_named_thing")
  some_named_thing.do_something()

well
1 - we have @onready for that.


@onready var some_named_thing = preload("somename"+.tscn).instantiate()

2 - use static casting. you can assign the variables later:


var some_thing : PackedScene

func _ready() -> void:
     some_thing = load("somename"+".tsnc")
     var tmp : Control = some_thing.instantiate()

3 - or you can use an array:

var my_arr : Array

func _ready() -> void:
    for i in ResourceLoader.list_directory("path"):
         my_arr.append(load(i))
2 Likes

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