Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Accessing Database Object Fields Using Strings.

Discussion in 'Scripting' started by salehi-gamedesign, May 4, 2020.

  1. salehi-gamedesign

    salehi-gamedesign

    Joined:
    Apr 30, 2018
    Posts:
    15
    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:

    Spell activeSpell = spellDatabase.GetComponent<SpellDatabase>().fire;
    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.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,971
    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:

    Code (csharp):
    1. public enum SpellNames
    2. {
    3.   SpellFireBall,
    4.   SpellMagicMissile,
    5. }
    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:

    https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2

    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.
     
    salehi-gamedesign likes this.
  3. salehi-gamedesign

    salehi-gamedesign

    Joined:
    Apr 30, 2018
    Posts:
    15
    Thanks for the help, I opted for the first enum approach suggested.
     
    Kurt-Dekker likes this.