Many Unity code samples use a string identifier, such as the game object’s tag for various things (e.g: checking for a collision with “player”). In this post i will explore a different, safer and automated technique that achieves the same result, but does not require using strings.
The String Problem
Consider the following code:
var player = GameObject.FindWithTag("Player");
The code is not type safe: it relies on a string identifier to perform an object lookup. This identifier may change, making this code “out of sync” with the project, or be misspelled, making the code fail. In addition, this string might be used in many different locations of the code, increasing the risk of previous mentioned concerns.
A Solution “Sketch”
A possible solution to this issue is to create a static helper class that will expose all tags as public (static) fields. When needed, Instead of using a string, we’d use the class’s static fields:
public static class Tags { public static readonly string Player = "Player"; }
Accessing this tag is safer now, since we’re not (directly) relying on the string representation of the tag:
var player = GameObject.FindWithTag(Tags.Player);
Effectively, the code will operate the same as before, but now we have a single location where the tag is declared.
There are 2 main issues with this approach:
- In case there are many tags defined in the project, creating the helper class can be a somewhat tedious task (creating a field per tag).
- In case a tag’s name changes in the Unity editor, you have to also remember to replace it’s corresponding value in the helper class.
It seems that this solution is a step in the right direction, but we need some extra “magic” to make it perfect.
Code Generation To The Rescue
Code generation is an (sometimes) overlooked practice, where code is being automatically generated by some other code, a template or some tool.
In particular, code generation really shines in cases where we want to generate long, repetitive code from an underlying data source.
Translating this to the problem described above, we would like to generate a static helper class with many static fields from an underlying data source (a collection with all of the project’s tags).
To achieve this, we’ll use one particular implementation of a code generation engine called T4:
T4 is a template engine that comes with Visual Studio (which also heavily relies on it for various tasks), and also comes out of the box with Mono (yes, the same one that is installed with Unity).
A T4 template is a file (with a .tt extension) that mixes a body of text with special directives. The template generates a single output file (usually, a code file, although it can generate any other file format).
T4 Templates
In order to add a T4 template to your project, right click on your code project in MonoDevelop, and select: Add->New File. T4 Templates can be found under Text Templating on the left:
T4 Template Types
There are 2 types of available templates (ignore Razor templates as they’re irrelevant for this discussion):
- T4 Template – a template file that gets transformed during compilation time into the output file. This type of template is used to generate code files that are needed at design time (e.g: think of Microsoft’s Entity Framework, where a set of classes can be generated at design time from a database, instead of being created manually by the developer).
- Preprocessed T4 Template – a template file that creates an “intermediate” class that can later be used to generate the output code file.
Unity currently does not support adding T4 templates (.tt files) to scripting code – after compilation, all .tt files will be dropped from the code project (I reported this bug here: T4 Bug)
This forces us to use option #2 – creating a one-time “intermediate” class. This class will be used by a Unity edior extension, from which we can generate the class we want and add it to the project.
Show Me the Code!
Here is the preprocessed T4 template that will generate the Tags class for us (although the provided sample uses the same template to generate a Layers class in exactly the same manner):
A few things that should be noted:
- Any text that not contained within <# #> tags is being output as is.
- The template is a preprocessed template. This means it does not generate an output code file directly. Instead, it generates an intermediate (partial) class with a TransformText() method that returns the template final output (the text with the generated class).
- The code prints out a header (the class declaration with some comments), then it iterates all elements in source and outputs a public static readonly field for each item (does a small manipulation to make sure the field name does not have spaces in it).
- The variables classname, item and source are actually implemented in a code file (a partial class with the same name as the template class. Remember I said the template generates a partial class? this allows mixing the template with some custom code. For more clarity, see the full code in the link below).
In Conclusion
This post aimed to open a hatch to the wonderful world of code generation (and T4 in specific), while showing how it can solve real world problems in a short and simple way.
I did not dive into T4 syntax or more advanced topics (leaving it for you to explore, or as a subject for future posts). For more information regarding T4 – see the links below.
Links
- Unity package that demonstrates the solution from this post – http://goo.gl/ijXeD0
- Full code demonstrated in this post – https://bitbucket.org/liortal/unity-t4
- Runtime text generation with T4
- Preprocessed T4 templates
Great post Lior,
In our case, I think one of the best things you can do with this approach is easily and safely create layer bit masks for ray-casting.
e.g. Automatically generate a ‘layers’ class (contains all layers in the game), and a ‘masks’ class (contains bit masks for all layers & combinations).
hmmm something happened and my comment was reported as spam … would you mind checking please?
Thanks for the comment. I was merely accepting the usage of the tag feature for identifying objects, you are suggesting a different approach. Your suggestion though requires more setup work to be done – encapsulation of scripts and creation of prefabs, and finally “dragging” the prefab objects onto this static singleton context object. I suppose you could use my method somehow (slightly modified version of it) to populate the GameContext class with all the prefabs (how will you identify the prefabs that should be added to this class as fields?)
Very helpful post. My project somehow became corrupted and I was researching how not to recreate all the tags from scratch again. Your approach was also helpful in helping me create a DebugCategory class that allows me to easily color code the debug log. Thank you!
So I’ve been trying to generate a simple data structure using preprocessed templates, and found this blog. As of today in 2016 the Unity Editor supports CodeDOM Generation. https://msdn.microsoft.com/en-us/library/ms404245(v=vs.110).aspx
Anyhow, this has been a great resource for me. Thanks.