Sponsored By

Code Generation Fun with Unity

Many Unity APIs rely on string identifiers as part of their operation. In this post i aim to show a different, safe and automated way to handle these cases using code generation.

Lior Tal, Blogger

March 11, 2014

11 Min Read
Game Developer logo in a gray background | Game Developer

This post was originally posted on my blog at http://www.tallior.com

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:

string_lookup

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:

static_class

Accessing this tag is safer now, since we’re not (directly) relying on the string representation of the tag:

safe_access

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:

  1. 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).

  2. 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).

46974122

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

T4 Template Types

There are 2 types of available templates (ignore Razor templates as they’re irrelevant for this discussion):

  1. 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).

  2. 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):

t4_example

A few things that should be noted:

  1. Any text that not contained within <# #> tags is being output as is.

  2. 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).

  3. 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).

  4. 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

Read more about:

Featured Blogs

About the Author

Daily news, dev blogs, and stories from Game Developer straight to your inbox

You May Also Like