Unity MultiTagging in 20 lines
Added 2017-01-17 18:06:11 +0000 UTCThere are some solutions on the Asset Store for multi-tagging. Some are free. They suck. Here's my clean solution.
This leverages an Asset Store find that does NOT suck, though is somewhat out of date. Generic Inspector adds a ton of attributes that let you do some pretty fancy things in the Inspector without ever going near an Editor script
Now, then, the code itself...
First, the AI Manager. This is the singleton manager in which I define the global set of tags: http://pastebin.com/We6PdDDd
You can ignore everything outside of the #region blocks, AND that Attribute [ ] block at the top, which is what makes it call the cache-updating function any time you're touching the AI component. Put that stuff wherever you like. All this class does for now is give me an easy place to define that array of AI Tags, and then does some work to cache that array into a form the Editor stuff can grab quickly, without it being re-generated constantly.
Now here's the other bit: http://pastebin.com/MYS2z9Di
That lives in my AI component, but again, put it wherever you like. Just remember that your class definition will need to have one of these at the top, to enable the Inspector stuff: http://pastebin.com/p3XGWtLa
Now, what does this do? It gives you an interface that looks like this: http://imgur.com/a/iu1Le
Every entry in the array will have a nice drop-down that auto-populates from your global list of defined tags. If you remove a tag from the global list, the next time you check your AI Tag list, you'll actually find that it invalidated the old tags. That's more an accident of the Generic Inspector stuff than intentional, but it does have the handy benefit of soft-enforcing not using orphaned tags.
You'll note this code sample lacks fancy GetByTags() or whatever functions, but that's mostly because that's all the easy stuff, and varies by application. The first thing I'll do from here is populate that list of tags into a hashed list, so that I'm not stupidly stepping through the entire array every time I want to know if something has a tag, but that's really all I need. Maybe you want to do other stuff with it? Who knows! But there, have fun.
Also, I'd love to hear opinions on whether Generic Inspector is clean/safe. I haven't dug much into the code. It works, and I'm comfortable using it because it only runs in Editor mode anyways, but still - hey, opinions are nice.
Comments
Megan Fox
2017-01-17 19:04:53 +0000 UTC