-
-
Save Novack/8536d34da6ddfdc220cc73ce4848b999 to your computer and use it in GitHub Desktop.
Unity sample MonoBehaviour explaining how to associate simple strings with enums.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.ComponentModel; | |
| using UnityEngine; | |
| public class EnumDescription : MonoBehaviour | |
| { | |
| public enum PlayerState | |
| { | |
| Unknown, | |
| [Description("Alive and kicking")] | |
| Alive, | |
| [Description("Dead as a duck")] | |
| Dead | |
| } | |
| // Start is called before the first frame update | |
| void Start() | |
| { | |
| var state = PlayerState.Dead; | |
| Debug.Log("Player is " + state.GetDescription()); | |
| } | |
| } | |
| public static class EnumExtensions | |
| { | |
| public static string GetDescription(this Enum value) | |
| { | |
| var type = value.GetType(); | |
| var name = Enum.GetName(type, value); | |
| if (name != null) | |
| { | |
| var field = type.GetField(name); | |
| if (field != null) | |
| { | |
| if (Attribute.GetCustomAttribute(field, | |
| typeof(DescriptionAttribute)) is DescriptionAttribute attr) | |
| return attr.Description; | |
| } | |
| } | |
| return name; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment