1

Why does this line of code (context below)

if (spellEnum == Spell.Fireball) return "Fire ball";

produce the error:

'Spell' is a type parameter, which is not valid in the given context

public abstract class DataSet : ScriptableObject
{
    public abstract string DisplayName<T>(T arg) where T : Enum;
}

public enum Spell { Fireball, Icestorm, MagicMissile };

public class SpellDataSet : DataSet
{
    public override string DisplayName<Spell>(Spell spellEnum)
    {
        if (spellEnum == Spell.Fireball) return "Fire ball";

        return "Other spell";
    }
}

public class DataLibrary
{
     void main()
    {
        SpellDataSet spellDataSet = new SpellDataSet();
        strint test = spellDataSet.DisplayName(Spell.Fireball);
    }
}

I want a generic way to access data about various types (spells, items, characters), with data about specific kinds of that type (Spell1, Spell2, etc) accessed via that type's respective enum (Spell), and a universal method (defined in abstract class) across all types will produce the user-friendly name (DisplayName).

1 Answer 1

1

I still don't understand why the original code produces an error, but I have achieved what I wanted via making the abstract class generic, rather than only the DisplayName method. Code that works:

public abstract class DataSet<T> : ScriptableObject where T: Enum
{
    public abstract string DisplayName(T arg);
}

public enum Spell { Fireball, Icestorm, MagicMissile };

public class SpellDataSet : DataSet<Spell>
{
    public override string DisplayName(Spell spellEnum)
    {
        if (spellEnum == Spell.Fireball) return "Fire ball";

        return "Other spell";
    }
}

public class DataLibrary
{
    void main()
    {
        SpellDataSet spellDataSet = new SpellDataSet();
        string test = spellDataSet.DisplayName(Spell.Fireball);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.