Unity: Tips on Code Documentation

This article offers some pointers on documenting a codebase within Unity. The last section generalizes documentation to validation and organization as well. This post assumes that you are using C#, though the same principles apply for other languages.

Naming Conventions

Before you begin writing code it is worth spending a little thought on how things (classes, functions, fields, even local variables) should be named. There are no hard and fast rules for this, but if you develop a policy early, then you will be thankful months later when you try to understand the code. With that said, here are a few points about naming that are highly encouraged, because they are widely adopted:

XML Documentation

C# uses XML Documentation for its code -- if you include comments in XML, then your IDE can read them and display them back to you in a meaningful way when you need to refer to methods or classes. Many IDEs will create skeleton XML for you when you type three consecutive forward slashes on the line above a method or class declaration.

Below is an example function signature with XML Documentation prepended to it.

/// <summary>
/// Releases a burst of multicolored particles centered on the GameObject
/// </summary>
/// <param name="intensity">How dense the particles are, from 0.0 to 1.0</param>
void BurstParticles(float intensity) 

Now, viewing this function from the IDE's code completion module will display the XML we just wrote.

Documentation exposed through MonoDevelop

Documentation exposed through MonoDevelop

When multiple people collaborate on the same codebase, XML Documentation becomes a powerful tool. It is recommended that you develop a policy for always documenting classes and certain methods; some methods, such as getters and setters, will be so mundane that they are not worth documenting, but in most cases small summaries will help developers understand the code more quickly. XML Documentation can also be used for fields, though tooltips (read on) may be a more useful option.

Unity Inspector Customization

So far, we have discussed documenting C# code without mentioning Unity. However, the Unity API does provide mechanisms for documenting, validating, and organizing scripts in a way that makes them more usable by the Unity Editor (specifically, the inspector). Below is a list of some attributes that serve this purpose.

Many of these attributes are simple to set up and require little maintenance after the fact -- you just need to remember to keep using them consistently, and your scripts will become much more usable.

Back