- Home /
[Inspector] Populate Enum Options with List of Files?
I'd like to populate the options in an enum list based on the files inside a folder.
Here's the current code:
enum Attacks {Option1, Option2, Option3}
var attackChoice : Attacks;
Instead of hard-coding the options, I want the list to include every Prefab I've created inside my "Attacks" folder. That way, as I create new "Attack Prefabs", they are added to the list for selection.
Is this possible?
Answer by Jamora · Sep 28, 2013 at 10:58 AM
Modifying the contents of an enum is not possible during runtime. Doing that would defeat the whole purpose of an enum, which is to list - or enumerate - every possible option available at any given time during runtime.
What you can do, is read the contents of your folder, then add those files to a list or other data structure, whose contents you then show in your inspector.
Just to add to this - Enums are simply a compile-time construction. They exist to aid the programmer in making code more readable, by assigning names to numerical values, and limiting the range of available numbers. If you have an enum the same as your current one (with 3 options), writing Attacks.Option1
is functionally equivalent to using the integer value 0 (and in fact you can cast between these two types to get/use these values). When you compile the code, it removes the enumeration and replaces it with just the numbers (in simple terms, anyway), so changing the enum at runtime makes no sense, as there isn't really anything there to change.
The purpose would be to make it just a bit easier for me or other programmers working with the scripts. The prefab-list would be a list of available particles, or perhaps a list of available weapons, so rather than having to click/select or drag the prefab into the field, the programmer would just select from the list, and when a new weapon is added to the list, it's also available in the selection list. So it's not intended to make any real changes in the game, just in the inspector while building the game.
You can do this in other ways, without using enums, as it is literally impossible to alter an enum beyond compile time (which is what you're trying to do - edit mode is still in runtime). You can search through specific folders and create a list of prefabs that way, then create a custom dropdown box, which you can populate with members of this list. Enums are a static construct, and not useful for dynamic data. That's what data structures like lists are for.
Do you know what phrase I should be searching for to learn about that? $$anonymous$$y googling hasn't given me anything to go on that I know of.
You should look it up in several parts. Firstly is using a list or array as the elements in a Unity dropdown menu. Second is searching for all prefab files in a specified folder (or path). Third is looking up generic data structures such as List, LinkedList, Set and Dictionary.