- Home /
Enum with multiple fields
Hi, in Java you can declare "enums" using multiple fields, for example:
public enum Item {
POTION("Potion", "Gives health", 20),
HIGH_POTION("High potion", "Gives more health", 100);
Item(final string name, final string description, final int price) {
...
}
}
Is this possible in Unity too? It would be very useful! Right now I'm using methods with huge switches, but I'm starting to have too many lines of code...
Thank you!
Answer by tuinal · Jul 30, 2020 at 04:36 PM
Unity uses C#, so the question is more whether it's doable in C#.
I think what you mean is whether it's possible to have enum classes - it is.
https://docs.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/enumeration-classes-over-enum-types
What you might actually want though is e.g. a 'Consumable' base class, with certain generic properties (which could be enums or anything else); then an inheriting 'Potion' class, with properties specific to all potions, then an inheriting HealingPotion class, etc, etc. This is because usually in game programming logic is often coupled closely to hierarchical type (e.g. all consumables might be 'usable' on pressing E; if it's of subtype 'Potion' then you might want to play a drink animation; if it's a healing potion you might want to boost Player.hp etc.). You can use polymorphism for this rather than trying to explicitly work out what something is and have a huge length of code switching/if conditions.
Answer by Cloudy71 · Jul 30, 2020 at 04:40 PM
C# doesn't support such thing. One of your options is to make static readonly fields.
public static readonly Item Potion = new Item("Potion", "Gives health", 20);
...
Or you can play with attributes and do thing like
[ItemAttribute("Potion", "Gives health", 20)]
Potion,
...
Depends on what would you like more.
Your answer
Follow this Question
Related Questions
Enum with multiple fields 1 Answer
Problem accessing enum from other class 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers