Coding Standards

Naming

Names should be descriptive; avoid abbreviation, within reason. Do not worry about saving horizontal space as it is far more important to make your code immediately understandable by a new reader. Do not use abbreviations that are ambiguous or unfamiliar to readers outside your project, and do not abbreviate by deleting letters within a word.

Variables

Unity's Editor expects variable names to be done in Microsoft Camel Case. For example, the Unity Editor will convert firstName to First Name in the Unity inspector, so camel casing is important or it would say FirstName or first_name. Use camel case to keep it easy to read in the editor.

For this reason, variables that are public or set with [SerializeField] should start with a lower-case letter, and camel case the rest; backgroundColour, paletteColour, rotatationSpeed, etc.

Private variables should be suffixed by an underscore() for example; sliceMesh, intensity, firstName.

One of the advantages of Unity is the editor inspector. When creating variables that are shown in the inspector we need to think about how the user will see and interact with these. Unity has many extra tools for helping with this.

  • Serializing fields to expose variables in the editor but not have to make them public within the code.
  • Header tags to separate variables into chunks.
  • Tooltip tags to give more information about an item or what it does when the user hovers over it.
  • Limiting Input Values

This is by no means an exhaustive list but it is a decent starting ground.

    [Header("Editor Settings")]
    [Tooltip("Arbitary text message")]    
    public string onClickText = "";
    [Tooltip("Useful GameObject you might need.")]     [SerializeField]     GameObject usefulGameObject;
    [Range(1,6)]     [SerializeField]     int rangeVariable;
    private float amountOfFrustration_;

Class or Types

Classes, Types and Functions should be named using Microsoft Pascal Case, start with a capital letter and have a capital letter for each new word. Captialise common acronyms as single words.

public class ExampleUnityScript : MonoBehaviour {
    public void TurnSlice(float amountOfRotation) {
    }
    public bool CheckLevelCompletion() {
        return false;
    }
    void GenerateUi() {
    }

Enumerators

Enumerators both scoped and unscoped enums should be named with a preceding k and each following word captilaised.

    enum DmgType {
        kHot,
        kCold,
        kBurn,
        kWater
    }

Formatting

To keep everything organised group everything into sections, and keep it ordered and spaced neatly

  • Fields (Variables)
  • Properties (Getters/Setters/Accessors)
  • Event (Event and listener declarations)
  • Functions
    • Unity Functions
    • Class Specific
  • Private interface implementations
  • Nested types.

Each section should be ordered by accessibility; Public, Protected, Private. Serialized variables should be ordered with public variables so as to be shown in a sensible way in the editor.

Braces and Spacing

There is a handy settings file for Visual Studio 2015 on our OneDrive folder OneDrive Link. That sets up braces and spacing, use ctrl + k, ctrl + d to format a document to these settings once imported.

The main thing to think about when bracing and spacing is ensuring it is sensibly spaced and easy to read, even if this means adding brackets and spaces to an if statements conditions. The first line should contain the opening brace with the final brace always on a new line for all classes, statements, functions etc.

If Else

        if (setA == setB) {
        }
        else {
        }

If statements should always have braces even if only one line within in said braces. There should be sensible spacing between IF statements conditions.

Switch

        switch (damageType) {
            case DmgType.kHot: {
                    break;
                }
            // ...etc
            default: {
                    break;
                }
        }

Switch cases should be tabbed in 4 spaces, each Case should have opening and closing brackets. The internals of a case should also be tabbed in. A switch case should have a default statement.

Comments

Comments will be used to explain what something does and why it does it this way. The code itself should be self documenting with descripitive names of functions, classes etc. However, proper commenting will help make the code easier to go back to at a later date as well as provide usefull information in intelisense when calling our own functions.

The formatting of comments will follow the XML C# Commenting style this provides intelisense tips for functions. The comments will explain how to use the classes, and functions with any extra usefull tips. For example explanation of why it needs certain params, and why it returns a value. There is a few handy tags for adding more information C# Commenting Tags.

Class

/// <summary>
/// This is a basic example class for learning commenting spacing
/// and best practices for 3rd Year Project of Team19.
/// </summary>
public class ExampleUnityScript : MonoBehaviour {  

Functions

             
    /// <summary>
    /// Desciption of what it it does and why.
    /// </summary>
    /// <returns>What the return value means, and why it returns its value.</returns>
    public bool CheckLevelCompletion() {
        return false;
    }
    void GenerateUi() {        
        if (amountOfFrustration_ < rangeVariable) {     // Explanation of steps can be added at the end of a line.            
            amountOfFrustration_ ++;                    // The start of following explanation should line up underneath each other.
        } else {

        }
    }

Variables

    /// public and serialized variables should have tooltips describing in more detail what they are for.
    [Tooltip("Useful GameObject you might need.")]
    [SerializeField]
    GameObject usefulGameObject;
    
    /// <summary>
    /// Variables may have an extra comment for extra info, but variable name should be self explanatory
    /// </summary>
    private float amountOfFrustration_;  

Params

      
    /// <summary>
    /// This extra bit would explain what the functon does.
    /// </summary>
    /// <param name="amountOfRotation"> explanation of what the paramater is used for. and why it is needed.</param>
    public void TurnSlice(float amountOfRotation) {
    }

Line Endings

Every file should have Unix-style line endings. If you get warnings in Visual Studio about line endings please set them to Unix Line Endings. This is to ensure everything runs smoothly dependent of OS.

Committing Code

Warnings

All code warnings should be fixed, there shouldn’t be any code warnings in committed code. Merge requests will be rejected if there are code warnings.If you are not using a variable, Delete it.

Some exceptions to this are the way Unity Handles Serialized variables, as this will show an initialised warning in visual studio which cna generally be ignored. but each of these will be discussed at merge requests.

Merge Request

Anything being merged must be finished code, no unused code, or commented out code. Every variable, class and function must be named, spelled and commented sensible and correctly for the merge request to succeeded, there will be discussion on the merge request on what needs changed by all coders before being merged.

Strive For

This is some coding practices to read up on that this project will strive to meet in the long term. They will also be used to review code and look for possible areas of improvement.

Useful Tools

List of handy extensions for use with Visual Studio 2015.

MonoDevelop of course can easily be used for development in Unity as well, though some of the tools of VS 2015 are handy when programming.