using a variables string value as part of the name of other variables

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

I am trying to make a variable that will hold the type of weapon the player has equipped as a string and have different weapon types have varying skill levels that affect the damage done. so say you have a sword skill of 2 and a club skill of 1 i want to be able to call in the weapon type to determine which variable is being used. in my head it looks something along the lines of…

var weaponType = “sword”
var swordSkill = 2
var clubSkill = 1

func attack():
enemyHealth -= 5 + (weaponType+skill)

as is the case with many things for me this doesnt translate properly to the code because i am not entirely sure of the correct syntax for it.
thanks for any and all help

:bust_in_silhouette: Reply From: Adrasteon

You should use a single variable.
Follow these steps:

  • If you need only a single variable for your weapon, use an enum:
    • Define this enum: enum Weapon { SWORD = 1, CLUB = 2}
    • Use this variable: var weapon = Weapon.SWORD
    • Get the int value: weapon as int
    • Get the string value: Weapon.keys()[weapon]
  • If you need to attach more variables to your weapon, consider using a resource:
    • Create a custom resource class
    • You can then create a resource file per weapon in your project
    • To use the weapon of your choice in a given script, add a variable that can be set from the editor: @export var weapon : Weapon
    • You can follow the beginning of this tutorial (for Godot 4 use “@export” instead of “export”)

thank you for the insight i will look into the resources as i feel that will be most helpful.

dellfenian | 2023-04-19 19:55