Table of Contents

Every programming language has its own widely accepted coding standards, which define best practices for syntax, formatting, and general code organization. These language-specific standards provide a solid foundation, but each company or project often expands upon them to meet their own needs.

I’ve previously shared the importance of creating detailed style guides for game development projects. One such guide, the Technical Style Guide, defines the programming language and coding standards to be used on a project, along with workflow conventions and other technical rules. Within this framework, a Script Style Guide further specifies how individual scripts should be written, including naming, formatting, commenting, and organization.

Script Style Guide

A script style guide goes beyond naming conventions for classes (which we’ve already covered) to include naming schemes for variables and methods, combining language-specific coding standards with project-specific rules to ensure consistency and readability. It also outlines formatting specifics, such as:

  • Commenting conventions: How and when to add comments, what types of comments are required (e.g., method summaries, inline explanations), and preferred formatting.
  • Namespaces and file organization: How scripts should be grouped into namespaces or folders to maintain clarity and consistency.
  • Method structure: Preferred ordering of methods, use of access modifiers, and spacing for readability.
  • Other formatting rules: Indentation, line breaks, and other stylistic choices that make the code easier to read and maintain across the team.

By defining these standards clearly, a script style guide ensures consistency, improves collaboration among developers, and makes maintaining and expanding the codebase much easier over time. Most companies have their own standard script style guides, and I have developed one for my courses that all students adhere to. Not only does this help students get used to following a consistent standard, it also makes grading simpler and more objective.

Unity Script Style Guide

The following guide defines my personal script style standards for Unity game development projects. While Unity has recently developed its own official style guide, this guide includes slight differences tailored to the requirements of the courses I teach.

It builds on standard C# coding conventions, ensuring that scripts are consistent, readable, and maintainable, while also making it easier for students to follow a unified standard across all assignments.

C# Coding Standard

In general, the standard Microsoft C# Coding Conventions will be implemented. A few standards to be aware of include:

Basic Principles

When writing scripts, following a few fundamental principles can make your code easier to read, maintain, and extend:

  • Object-Oriented Principles: Apply encapsulation, abstraction, inheritance, and polymorphism appropriately.
  • Principle of Least Surprise: Choose solutions that are intuitive and easy for others to understand.
  • Keep It Simple, Stupid (KISS): Use the simplest solution that works—avoid unnecessary complexity.
    • Line Length: Keep lines under 130 characters for readability.
    • Class Size: Keep classes under 300 lines to stay focused and manageable.
  • You Ain’t Gonna Need It (YAGNI): Solve the problem at hand rather than anticipating unlikely future requirements.
  • Don’t Repeat Yourself (DRY): Avoid duplicating code or logic; reuse components where possible.
    • Instead of repeating the same health calculation in multiple classes, create a HealthManager class that all systems can use.
  • Single Responsibility Principle (SRP): Each class or method should have one clear purpose. This makes your code easier to test, debug, and maintain.
    • A class that handles both player movement and inventory management is doing too much. Split it into smaller, focused classes: PlayerMovement and InventorySystem.

Keeping scripts small and focused makes them easier to test, debug, and maintain — which is exactly what professionals do in real-world projects.

Imports/using statements

  • Namespace using declarations go at the top, before any namespaces. 
  • Remove unused using directives.
  • Order them logically (system → Unity → project).

Explicit access modifiers

  • Always write public, private, or protected.
  • Don’t rely on defaults—it makes code clearer for others.

Constants and Enums

  • Use const, readonly, or enum to make values meaningful and maintainable.
  • Avoid “magic numbers” or strings.

Magic Numbers

A magic number is a raw value written directly in code without context. It’s “magic” because no one knows what it means or why it’s there. Using a named constant makes the code clear, consistent, and easier to maintain.

❌ Example: Why are we comparing to 37?

if (health <= 37)
{
    Debug.Log("Game Over!");
}

✅ Better: Defining what 37 defines is much clearer

private const int MINIMUM_HEALTH = 37;

if (health <= MINIMUM_HEALTH)
{
    Debug.Log("Game Over!");
}

Just like magic numbers, avoid hardcoding strings that may be reused.

Formatting Conditional Statements

  • Always use braces { } for if, for, while, etc., even if it’s a single line.
  • This prevents mistakes when more lines are added later.
// Bad ❌ 
if (isAlive) Respawn();

// Good ✅ 
if (isAlive) 
{ 
    Respawn(); 
} 
  • Always check for null before using objects that might not exist (very common in Unity).
  • Always add a default block after the last case in a switchstatement
  • Finish every if-else-if statement with an else clause
  • Use a Simple Conditional Instead of if-else for Assignments
    • Use a ternary operator ? : for conditions that are meant only for simple “yes/no” decisions, where you want to assign a value based on a single condition. Example: string status = (health > 0) ? "Alive" : "Dead";

Class Design

Classes are the building blocks of object-oriented programming, defining the structure and behavior of objects in your Unity projects. A well-designed class encapsulates related data and functionality, making code easier to understand, maintain, and extend. Good class design follows the principle of single responsibility, meaning each class should focus on a clear and specific purpose. By organizing code into cohesive, modular classes, developers can promote readability, reduce complexity, and improve collaboration in larger projects.

  • One core class per file.
  • Filenames and directory names are PascalCase, e.g. MyFile.cs.
  • File name must match the class name exactly (case-sensitive).
  • Class names should be in the form of a noun
  • Class names should be written in PascalCase

See additional Class naming conventions.


Documentation comments

While many developers use version control to track changes and versions, documentation comments are a useful tool to quickly identify the class’s purpose and usage, see who last worked on it, and identify its purpose. They can also include copyright details and project references.

In classroom settings, documentation comments are especially important to ensure students include assignment-specific information.

Guidelines:

  • Placement: All classes should begin with documentation comments before the namespace or class declaration.
  • Format: Documentation comments should be formatted as follows:

/************************************************************
* COPYRIGHT:  Year
* PROJECT: Name of Project or Assignment
* FILE NAME: #SCRIPTNAME#.cs
* DESCRIPTION: Short Description of script.
*                    
* REVISION HISTORY:
* Date [YYYY/MM/DD] | Author | Comments
* ------------------------------------------------------------
* 2000/01/01 | Your Name | Created class
* 
*
************************************************************/ 


Coding Comments

Coding comments provide context and explanations for how and why code is structured in a certain way, supporting both your future self and other developers who may work on the project. They help clarify the intent behind classes, methods, and variables, reducing confusion and making it easier to debug or expand functionality later. Clear documentation is especially important in team-based or long-term Unity projects, where readability and maintainability are critical.

  • Use XML documentation comments for public classes, methods, and properties
/// <summary> 
/// Moves the player in the given direction. 
/// </summary> 
/// <param name="direction">The direction vector to move.</param> 

public void Move(Vector3 direction) { ... }

  • Use inline comments sparingly to explain complex logic.
  • Inline comments should be on their own line and before the code they describe.
  • Use clear and descriptive names for variables and methods, and avoid comments that repeat the code.
  • Keep comments up to date; always update or remove comments when code changes

Class Variables

Class variables are attributes that are shared across all instances of a class in object-oriented programming. They are defined within the class itself and typically hold values that are relevant to the class as a whole, rather than to individual objects. By using class variables, developers can manage shared state and behavior efficiently, ensuring that any changes made to the variable affect all instances uniformly. This promotes cleaner code and facilitates easier maintenance, making class variables a crucial aspect of organized programming.

All Variables:

  • Name types using nouns, noun phrases, or adjective phrases
  • Avoid short names or names or abbreviations that can be mistaken for something else

Public Class Variables:

  • Written in PascalCase (capitalizing the first letter of each word).
  • Should be clearly descriptive.
  • Example: public int PlayerScore;

Private Variables:

  • Written in camelCase with an underscore prefix.
  • Should be clearly descriptive.
  • Example: private int _playerHealth;

Protected Variables:

  • Protected variables are essentially private variables that are accessible by subclasses.
  • Written the same as private variables
  • Example: protected float _speed;

Constants:

  • Constants are fixed values that cannot be changed at runtime.
  • Constants are declared using the const keyword and must be initialized with a value when they are declared.
  • Constants are typically used for values that are known at compile-time and are not expected to change during run-time
  • Example: public const float PI = 3.14;

Static Variables:

  • Static variables are variables that belong to the class and are shared by all instances. If a static variable is modified by one instance of the class, it will also be reflected in all other instances.
  • Static variables are declared using the static keyword and can be accessed using the class name without needing to create an instance of the class. This is because a static variable can only have one value.
  • Written in ParcaleCase with a s_ prefix.
  • Example: public static int s_PlayerCount;

Booleans:

  • Should always ask a question that leans towards a true statement.
  • Should be named as descriptive questions.
  • Example: public bool IsPlayerAlive;

Methods

Methods are functions defined within a class that outline specific behaviors or actions that an object can perform. They allow for the encapsulation of functionality, promoting code reuse and modular design. By using methods, developers can create clear interfaces for interacting with objects, making it easier to manage complex systems. Understanding how to define and utilize methods is key to writing effective object-oriented code, as it enhances readability and simplifies the process of debugging and maintaining software applications.

Method Names:

  • Written as verbs to indicate actions.
  • It should be clearly descriptive of the action performed.
  • Protected methods are private methods accessible to subclasses
  • Example: public void AttackEnemy() { }
  • Method using the virtual keyword in the base class can be overridden in subclasses using the override keyword.

Method Variables and Parameters

  • Variables declared inside methods and for method parameters use camelCase with no underscores.

✅ Example:

void MovePlayer(int speedValue) { 
    int currentHealth = 100; float 
    moveDistance = speedValue * Time.deltaTime; 
}

  • Keep parameter count low: Prefer 3 or fewer parameters; if more are needed, consider using a class or struct to group related values.
  • Optional parameters and defaults: When appropriate, use optional parameters with default values to reduce overloads.

This style guide is meant to serve as a solid foundation for writing clean, consistent, and maintainable Unity C# scripts. Every project and team may have its own specific requirements, and you should always adapt these standards as needed to fit the scope, style, and goals of your work. This guide is intended to be used as a starting point: a shared framework that helps establish consistency while leaving room for growth and customization. By following these principles, you’ll be better prepared to collaborate effectively, build scalable projects, and write code that is both functional and easy to understand.

Categorized in:

Tagged in: