I am trying to reference enums by using a string with GetType(). I can’t seem to figure out why this doesn’t work when the class and enum are in a namespace. For example:
namespace MyNamespace
{
public class MyClass
{
public enum MyEnum
{
Value1,
Value2,
Value3
}
}
}
My code:
string[] list = Enum.GetNames(Type.GetType("MyNamespace+MyClass+MyEnum"));
Without the namespace, this works fine. Is there a different way to get the namespace or something?
This is a C#/.net specific method independent of Unity specifically.
Refer to MSDN documentation for documentation pertaining to such things:
Here it’ll give you a break down of the delimiter uses for the string passed to this method.
…
Of course this is mostly useful if you’re reading in the string from somewhere (say you serilized the type). If you’re in C# you don’t need to parse the string you could just say it directly:
string[] list = Enum.GetNames(typeof(MyNamespace.MyClass.MyEnum));
or
string[] list = Enum.GetNames<MyNamespace.MyClass.MyEnum>();
Using periods doesn’t work. When simply doing, MyClass+MyEnum, the plus sign works. not the period. Idk.
I am doing this because I have a UI properties panel that needs to display properties for a wide variety of objects and referencing enums from components is one thing I need to do. Instead of adding enums to the code, one string variable in my scriptable objects can reference which enum is needed. I may resort to just doing an array of enums which the S.O. can reference just as easy, but I will need to add each enum to the array manually.