Skip to content

Enums

SyntaxDescriptionNote
public enum Mode { Off, On }Declaring an enum
enum Code { Ok = 200, NotFound = 404 }Explicit values
enum Small : byte { A = 1 }Specifying the underlying type
[System.Flags] enum Perm { Read = 1, Write = 2 }Combining (Flags)
public Mode M;Holding as a field
Mode[] ms = new Mode[2];Array element
struct Holder { enum Mode { … } }Declaring inside a type
SyntaxDescriptionErrorReasonAlternative
m.ToString()Turning a value’s name into a stringTUKI0001undecidedWrite a method that returns the name with switch
$"{m}"Embedding the name of a value in a stringTUKI0001undecidedEmbed (int)m if the number is enough. If you need the name, write a method that returns it with a switch
"x" + mEmbedding a value’s name into a stringTUKI0001undecidedEmbed (int)m if the number will do. If you need the name, write a method that returns it with a switch
string.Format("{0}", m)Embedding the name through a format stringTUKI0001undecidedIf a number is enough, embed (int)m. If you need the name, write a method that returns the name with switch.
How the value is representedIt travels as an integer. The value itself is used normally, but it carries no name at runtime, so taking the name out as a string doesn’t compile
[System.Flags]It applies when printing the name, so it changes no output in this runtime (the combining | can be written without this attribute)
using UnityEngine;
using Tsukimi;
public enum Mode { Off, On }
public class TyEnumDeclare : TsukimiBehaviour
{
void Start()
{
Mode m = Mode.On;
Debug.Log((int)m); // => 1
}
}
using UnityEngine;
using Tsukimi;
public enum Code { Ok = 200, NotFound = 404 }
public class TyEnumExplicit : TsukimiBehaviour
{
void Start()
{
Code c = Code.NotFound;
Debug.Log((int)c); // => 404
}
}
using UnityEngine;
using Tsukimi;
public enum Small : byte { A = 1 }
public class TyEnumUnderlying : TsukimiBehaviour
{
void Start()
{
Small s = Small.A;
Debug.Log((byte)s); // => 1
}
}

Adding [System.Flags] doesn’t change how | combines values (Forms that don’t compile).

using UnityEngine;
using Tsukimi;
[System.Flags]
public enum Perm { None = 0, Read = 1, Write = 2 }
public class TyEnumFlags : TsukimiBehaviour
{
void Start()
{
Perm p = Perm.Read | Perm.Write;
Debug.Log((int)p); // => 3
}
}
using UnityEngine;
using Tsukimi;
public enum Mode { Off, On }
public class TyEnumField : TsukimiBehaviour
{
void Start()
{
M = Mode.On;
Debug.Log((int)M); // => 1
}
public Mode M;
}
using UnityEngine;
using Tsukimi;
public enum Mode { Off, On }
public class TyEnumArray : TsukimiBehaviour
{
void Start()
{
Mode[] ms = new Mode[2];
ms[0] = Mode.On;
Debug.Log((int)ms[0]); // => 1
}
}
using UnityEngine;
using Tsukimi;
public struct Holder { public enum Mode { Off, On } }
public class TyEnumNested : TsukimiBehaviour
{
void Start()
{
Holder.Mode m = Holder.Mode.On;
Debug.Log((int)m); // => 1
}
}