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)

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.

in Engine by (197 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

    # 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))
by (27,898 points)
edited by
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.