How to acces a dictionary with a string

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By chantunRey

So I have a few dictionaries that are enemies and an array from I randomly choose one of their names. When I want to print, it gaves an error for being on base: string? Thanks in advance.

var enemies = ["rat", "dog", "puma"]
var currentEnemy

func _ready():
	currentEnemy = enemies[randi()%3]
var rat = {
	"nme": "Rat",
	"HP": 2,
	"attack": 1,
var dog = {
	"nme": "Rat",
	"HP": 6,
	"attack": 2,
var puma = {
	"nme": "Puma",
	"HP": 4,
	"attack": 8,

rakkarage | 2020-07-05 22:13

:bust_in_silhouette: Reply From: Jorge

Would you explain what are you trying to do with the code?

if in your code just use print(currentEnemy) that would give you an enemy, however, you need to add +1 to randi to give you a number from 1 to 3.

the way I would do a random selection of a enemy and get their values:

var enemies = {
               1: {"nme": "Rat", "HP": 2, "attack": 1,}, 
               2: {"nme": "Dog", "HP": 6, "attack": 2,},
               3: {"nme": "Puma", "HP": 4,"attack": 8,}

var currentEnemy = enemies[randi()%3+1]

func _ready():
	print (currentEnemy["nme"]," HP: ", currentEnemy["HP"], " AT: ", currentEnemy["attack"])

I hope it helps!

Thanks for your reply. I realized that it was that I declared the dictionary variables AFTER the function. thanks anyways

chantunRey | 2020-07-06 01:04

even if you change and declare de dictionary BEFORE gives you the same error, is a good practice to that but is the same, however, if it works for you now, great!

For me using the array for enemies and calling the dictionary keeps giving me error , I have to use my method.

good luck!

Jorge | 2020-07-06 06:12