0 votes

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 ?

in Projects by (403 points)

2 Answers

0 votes
Best answer

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.

by (1,968 points)
selected by
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 ?

0 votes

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.

by (194 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.