0 votes

This might be a bit confusing, but I'm trying to pull a value off a variable based on it's name. I have two variables that help with this.

weap_id (Weapon ID from 0 to 11)

weapon0
weapon1
weapon2
weapon3
Etc. (These contain the amount of ammo each weapon has)

Basically what I want the script to do is this:

if $ammo.value != weapon+weap_id:
    $ammo.value = weapon+weap_id

Attempting this give the following error, though:

Invalid get index 'weapon' (on base: 'Node (global.gd)').

Is there a way to combine these two so I can pull the value without typing each one out? I can get it to spit out the name if contained in str(). But that doesn't help pull the data either.

asked Aug 14 in Engine by 9BitStrider (153 points)

1 Answer

0 votes

In this situation you should use an array. Arrays are lists of variables with a defined number of elements in them. Each element is associated a numeric index so you can access them using that index: http://docs.godotengine.org/en/3.1/getting_started/scripting/gdscript/gdscript_basics.html#container-built-in-types

So you can do something like:

var weapons = []
var weap_id = 0


func _ready():
    # Give the array a size
    _weapons.resize(11)

    # Put 100 ammo in every weapon by iterating each element
    # Note: the `len` function gives the total size of the array
    for i in len(_weapons):
        _weapons[i] = 100


func update_value():
    if $ammo.value != weapons[weap_id]:
        $ammo.value = weapons[weap_id]

However, there is also a way to specifically do what you said. IMO it's a bad idea because it makes code harder to maintain in the long run, but you can get and set variables based on a procedural name using get and set:

 $ammo.value = get("weapons" + str(weap_id))
answered Aug 14 by Zylann (20,312 points)
edited Aug 14 by Zylann
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.