How can I reference one variable in another variable ?

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

I want to use value of a variable in another variable. For example let’s say that I have a variable enemyNumber = 1 and then I have another variable enemy.
Now is there any way I can join these two together ? I want enemy1. Is something like that even possible ?

:bust_in_silhouette: Reply From: Ertain

If you’re referring to combining the variables, that’s easy: use some form of math. For instance,

var enemy: float = 1.2
var enemyNumber: int = 1
var enemy1 = enemy + enemyNumber # enemy1 has the value 2.2

For strings, that’s easy, too: also use a form of math:

var enemy: String = "bad_guy"
var enemyNumber: int = 1
var enemy1: String = enemy + str(enemyNumber) # enemy1 has the value "bad_guy1”.

Things get messy when mixing data types. Arrays and dictionaries store groups of values, so the code would be different.

func _ready() -> void:

func spawn(var enemyNumber):
	while true:
		var enemy_1 = enemy1.instance()

This is what I am trying. Instead of 1 i want to use enemyNumber. Can I do that ?

Scavex | 2020-09-01 16:30

:bust_in_silhouette: Reply From: DaddyMonster

If I understand you right I think an array is what you need.

var enemies = []

func _ready():
    var enemy = load("<enemy_scene_file>").instance()

Now you have you enemy object in an array and you can append as many more as you like. You call them or set their position for example: enemy[0].global_transform.origin = Vector3(10, 0, 10) or whatever. size(enemies) will give the count of objs.

That’s doing it with objects mind. It’s usually better t0 handle pointers to the actual objects stored neatly in an array rather than abstract int and str variables about them buried throughout your code but it’s up to you.