- 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 Bunny83 · Jul 30, 2020 at 06:38 PM
No, that's not possible. In Java an enum (like anything else) is actually a class This usage is actually a quite strange and unusual usage.
An enum in C# is just a collection of named constant primitive values. The enum type itself is essentially just like an alias for that primitive type. When no type is specified the default underlying type will be "int".
So what an enum actually does is something like this: Imagine you have an enum and a variable of that enum like this:
public enum MyEnum : int
{
None,
Foo,
Bar,
}
// [ ... ]
public MyEnum val = MyEnum.Foo;
What that does is similar to this:
public static readonly int MyEnum_None = 0;
public static readonly int MyEnum_Foo = 1;
public static readonly int MyEnum_Bar = 2;
// [ ... ]
public int val = MyEnum_Foo;
However enums have the advantage that they represent their own type and you get some type safety. However all enum values are essentially just a primitive value and you can always cast such a value to it's underlying primitive type or vice versa.
So again, no, this is not possible with an enum. However if you have a lot of values you might want to think about switching to ScriptableObjects instead of using enums. I would recommend watching Ryan Hipple's Unite talk about ScriptableObjects. I marked the "enum timestamp", but I can recommend the whole talk if you have the time, even though the rest is a bit unrelated to your issue at hand.
ps: Here's the talk of Richard Fine that was mentioned by Ryan which might give you some extra insight.
Your answer
Follow this Question
Related Questions
Enum with multiple fields 2 Answers
Handling different combinations of enum selection 1 Answer
Problem accessing enum from other class 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers