Accessing Database Object Fields Using Strings.

I have a database script (SpellDatabase) containing various spells which are created from the class ‘Spell’. I can then call one of these spells from within another script to access the spell properties e.g. the fire spell:

projectileDamage = activeSpell.missileDamage;```

However instead of specifying the spell type manually through the code e.g. __*'fire'*__/__*'ice'*__ etc. I'd like to use the __string variable__, '**spellDamageType**' (this updates automatically to match the player's currently selected spell) to get the relevant field for the currently selected spell automatically.

I have tried:

```Spell activeSpell = spellDatabase.GetComponent<SpellDatabase>().spellDamageType;```

however this doesn't work. I expect that I need to convert '**spellDamageType**' into something else before I can use it. What is the correct way to do this?

Thanks.

If you want to index things by string, beware that you will put yourself in constant peril of mistyping strings, such as typing SpellFireball when you meant spellFireball, just for one example.

For that reason, it will ALWAYS be more reliable to actually track references by some other means, such as using an enum to ensure your string spelling is always correct:

public enum SpellNames
{
  SpellFireBall,
  SpellMagicMissile,
}

NOW, if you insist on looking things up by string, probably your best bet is to use a Dictionary collection that keys off a string, and contains values of whatever you want to link it to. Here is the Dictionary docs:

For ultimate reliability and flexibility, you can actually index the Dictionary by that enum type above, which will keep you out of trouble from mistypings. And you can always call .ToString() on the enum if you need to display it or compare it string-wise.

1 Like

Thanks for the help, I opted for the first enum approach suggested.

1 Like