Get_node().variable how?

Please help me, how can I use a variable when specifying the variable to be called during get_node?

var li = [“skelet”,“spyder”]
var pt = li.pick_random()

var a = pt + “_name”
var b = pt + “_hp”

var c = get_node(“/root/monsters”).a
var e = get_node(“/root/monsters”).b

Error (Invalid get index ‘a’ in monsters.gd)

I think it’s something like this

var another_scene= load(“res://anotherscene.gd”).new()

func abc():
var a = another_sicene.instantiate()
a.variable

I managed to solve it

var li = [“skelet”,“spyder”]
var pt = li.pick_random()

var name_enemy = get_node(“/root/monsters”).call(pt)[0]
var hp_enemy = get_node(“/root/monsters”).call(pt)[1]

In file “/root/monsters.gd”

# Skelet
func skelet():
return [skelet_name, skelet_hp]

var skelet_name = “Skelet” #0
var skelet_hp = 100 #1

# Spyder

func spyder():
return [spyder_name, spyder_hp]

var spyder_name = “Spyder” #0
var spyder_hp = 50 #1

I just started learning Godot, if this is not quite the right decision, I will be glad for advice

It’s best to not hard-code names of methods as strings and use ‘call’ method to call them.

I’d also avoid using get_node for same reasons. Instead, define an @onready variable at the top of your script that references that scene/node. If you drag the “monsters” node to your script file while holding CTRL and then release mouse button while still holding CTLR, the editor will add the variable for you, like so:

@onready var monsters = $monsters
var name_enemy
var hp_enemy

func _ready()
    var monster = monsters.random_monster()
    name_enemy = monster["name"]
    hp_enemy = monster["hp"]

In file “monsters.gd”:

var enemies = [
    {"name": "Skelet", "hp": 100},
    {"name": "Spyder", "hp": 50}
]

func random_monster() -> Dictionary:
    return enemies.pick_random()

Multiple ways to implement this, and multiple levels of abstraction you could have, but as far as exactly what you described, the solution above would make adding more monsters a lot easier.

Hope it’s helpful, cheers!

1 Like

you can also use autoloads

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