How do I reference an instance with a string

Godot Version

var characterInstances : Dictionary = {}
var characters = preload(“res://Characters.gd”)
var player = preload(“res://player.gd”)
var c1
var c2
var c3
var c4
var c5
var check = 15

Called when the node enters the scene tree for the first time.

func _ready():
var characterSelect = “”

player = player.new()
player.initializePlayer()
createCharacters()
characterSelect =  "c1"
var dict =str_to_var(characterSelect)
player.addParty(dict)
print("inParty:", player.inParty)
#print (player.calculate_total_health())

Called every frame. ‘delta’ is the elapsed time since the previous frame.

func createCharacters():
c1 = characters.new(“A”, “UnitName1”, “Warrior”)
c2 = characters.new(“B”, “UnitName1”, “Thief”)
c3 = characters.new(“C”, “UnitName1”, “Mage”)

##in player.gd###
var inParty : Array =
func addParty(characters) → void:
if inParty.find(characters) == -1: # Check if the character is not already in the party
inParty.append(characters)
print(“Added”, characters, “to the party.”)
else:
print(characters, “is already in the party.”)

Question

So I’ve created multiple instances c1, c2, c3, c4,c5. all of them have their own set of variables. if I were to use player.addParty(c1) it works fine. However if I want some flexibility where I can use a variable to do what I want something to be done, it throws an error. I tried to use the str_to_var but it throws a null (I’m assuming I’m not using its intended function). any ideas on how to work around this? is this approach to creating character instances fundamentally flawed?

Use a dictionary instead of separate variables for each.

Not sure what you’re tryng to do here. If you want to set c1 the currently selected character you can just do characterSelect = c1 and characterSelect will be a reference to that character.

But it’s var_to_str() that converts variabes into strings

It works! I’m… I’m not too sure why I made it a string in the first place…

1 Like

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