Skip to content

Instantly share code, notes, and snippets.

@Novack
Forked from Paul-JanPauptit/EnumDescription.cs
Created August 18, 2019 02:01
Show Gist options
  • Select an option

  • Save Novack/8536d34da6ddfdc220cc73ce4848b999 to your computer and use it in GitHub Desktop.

Select an option

Save Novack/8536d34da6ddfdc220cc73ce4848b999 to your computer and use it in GitHub Desktop.
Unity sample MonoBehaviour explaining how to associate simple strings with enums.
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