So I’m rather new to the idea of reflection. I think I vaguely understand how to search for all classes by type, but I haven’t the slightest idea of how to do the next part I need. I’d like to place my objects into categories and sub-categories as dictated by attributes, so I can create a selection menu. Kind of like how adding a window option to Unity’s editor would be like, “Window/MyCategory/MyWindow”.
Is there a built-in way to sort these, or do I have to manually take each class’ attribute and manage the strings myself?
If you mean “Sort” the way I think you mean – ordering which category and subcategory comes first – one way to do this could be using enums to define the attribute’s properties rather than strings.
When you go to use the attributes for sorting you can order them first by Category, then by Sub-Category with simple casting to a number like (int). In more advanced situations, you can use Enum.GetValues() to get the full list of values, and have complex sorting based on other factors.
When you use them for display, you can use the DescriptionAttribute on each enum value to define the display name for that category or sub-category.
I’ve used this pattern before many times in form-based windows applications. This example might not be exactly what you’re looking for, but hopefully it gets the idea across:
using System.ComponentModel;
public class CategoryAttribute : Attribute
{
public CategoryAttribute (Category category)
{
// ...
}
public CategoryAttribute (Category category, SubCategory subCategory)
{
// ...
}
}
public enum Category
{
[Description("Red")]
Red,
[Description("Orange")]
Orange,
[Description("Yellow")]
Yellow,
[Description("Light Blue")]
LightBlue
}
public enum SubCategory
{
[Description("Round")]
Round,
[Description("Square")]
Square
}