Skip to content
Tutorials Center
My learning

Topics

Lesson 166 of 182 ยท Advanced C#

C# in Games and Desktop

See how C# is used in games (Unity, Godot, MonoGame) and desktop apps (WPF, WinForms, MAUI): game loops, components, coroutines, ECS, GC pitfalls and MVVM, with runnable code.

C# started life as a Windows desktop language and is now one of the main languages of game development. Unity, the engine behind a huge share of mobile and indie games, uses C# for its scripts. Godot, MonoGame, Stride and others support it. On the desktop, C# powers Windows applications (WPF, WinForms) and cross-platform ones (.NET MAUI, Avalonia, Uno). The language is the same C# you have learned in this tutorial, but the way you structure programs is different: instead of "run, compute, exit", a game or UI program sits in a loop, reacting to time and events.

This lesson explains that shape. You cannot open a window or a 3D scene in our in-browser editor, so we will build the important ideas as console programs: a game loop, a component model, coroutines, an entity-component system and a UI view-model. The real frameworks (Unity, WPF, MAUI) appear as read-only snippets that you can try on your own machine.

The game loop

Every real-time program has the same heart: a loop that repeats once per frame. Each iteration it (1) reads input, (2) updates the world, and (3) draws the result. What varies is how much time each frame represents. A frame can take 16 ms on a fast machine and 40 ms on a slow one, so movement must be scaled by the elapsed time, called delta time: a character moving at 120 units per second moves 120 * dt units each frame.

Simple variable-delta updates make physics unstable (bigger steps behave differently), so most engines run game logic in fixed time steps and let rendering run at whatever rate it can. The standard pattern is the accumulator: add each frame's real elapsed time to a bucket, run as many fixed-size updates as fit, and keep the remainder. The program below feeds it made-up frame times so the output is the same every run (real code would read a clock).

C# Fixed-timestep game loop with an accumulator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Read the output. In frame 1 the real time (16 ms) is a hair less than one step (16.67 ms), so there is no logic tick yet, but the renderer draws the object slightly ahead, interpolating. Frame 2 took 40 ms, so three ticks run to catch up. Frame 6 was a 500 ms stall: it was clamped to 250 ms, which is 15 ticks instead of 30. The logic is deterministic: the same inputs produce the same positions regardless of how fast the machine is, which is what makes replays, networking and physics reliable.

Unity: C# inside an engine

In Unity you do not write Main. You write classes that derive from MonoBehaviour and attach them to objects in the scene. The engine owns the loop and calls your methods at the right moments. This snippet is read-only because it needs the Unity editor:

C#
// Read-only: Unity script (Assets/Scripts/Mover.cs).
using UnityEngine;

public class Mover : MonoBehaviour
{
    [SerializeField] private float speed = 2f;   // editable in the Inspector

    private void Start()                         // once, before the first frame
    {
        Debug.Log($"{name} is ready");
    }

    private void Update()                        // once per rendered frame
    {
        transform.Translate(Vector3.right * (speed * Time.deltaTime));
    }

    private void FixedUpdate() { /* physics step, fixed interval */ }
}

Things that are specific to Unity:

  • Lifecycle messages (Awake, Start, Update, FixedUpdate, OnDestroy) are called by the engine by name. There is no base-class method to override.
  • Unity's C# version is behind current .NET. Unity runs scripts on its own Mono or IL2CPP runtime, and its supported C# language version has long been around C# 9. Many features from this tutorial (C# 12โ€“14 syntax such as primary constructors or collection expressions) may not be available in your Unity version, so check the manual for the version you use.
  • UnityEngine.Object overloads ==. A destroyed object compares equal to null even though the C# reference is not null. Do not use ?. or ?? on Unity objects; they bypass that check.
  • Garbage collection pauses are visible. At 60 frames per second you have about 16 ms per frame. A garbage collection that takes longer than that shows up as a hitch. The golden rule is do not allocate in Update.
  • Async is different. Unity's main thread owns the scene, and most of its API may only be called from it.

The next two sections build the same ideas in plain C# so you can see how engines are put together.

The component model

Unity's central idea is composition over inheritance. Instead of a deep class hierarchy (Enemy : Character : Entity), a game object is an empty container and behavior is attached as components: a Mover, a Health, a Renderer. Each component has lifecycle methods that the owner calls. Here it is in about 30 lines.

C# A tiny component model with Start and Update

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Start ran once, Update ran every frame, and Health has no Update at all: it only reacts when something calls Damage. This uses primary constructors, generic constraints and virtual methods.

Coroutines are iterators

Games constantly need "do this, wait one second, then do that." Writing that as state variables in Update is tedious. Unity's coroutines let you write it as straight-line code with yield return. They are an application of the iterator blocks you already know: the method is a state machine that the engine resumes each frame. Here is a tiny scheduler that treats each yield return as "wait this many seconds".

C# Coroutines on top of yield return

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Both routines print spawn immediately, boom once a second has passed, and done half a second later. In Unity you write yield return new WaitForSeconds(1f) and the engine does what Scheduler does here. Because each call is a plain iterator, a coroutine costs one small object, not a thread.

Data-oriented design and ECS

The component model above stores each object separately in memory. A scene with 100,000 bullets has 100,000 GameObjects, each pointing to component objects scattered around the heap. Modern CPUs are fast at arithmetic but slow at following pointers to cold memory, so this layout wastes time on cache misses.

Entity-Component-System (ECS) flips the layout. An entity is just an integer id. A component is plain data (a struct), stored for all entities in one contiguous array. A system is a function that loops over those arrays. Moving every entity then touches two tightly packed arrays in order, which the CPU prefetches efficiently.

C# A minimal ECS with struct arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The ship moved four times, the bullet moved three times and was then destroyed (so its last position stays frozen), and the rock, with no velocity, never moved. Real ECS libraries add things this sketch skips: archetypes (groups of entities with the same set of components, stored together), safe entity handles with a generation number to catch stale ids, queries ("every entity with Position and Velocity"), and parallel execution of systems. Examples are Unity's DOTS/Entities package and community libraries for .NET such as Arch and DefaultEcs. The ref local on world.Positions[id] is from the unsafe-code lesson, and the readonly record struct types are plain records stored inline in the arrays.

Avoiding allocations in hot loops

Game code runs the same function tens of thousands of times per second, so a tiny allocation per call becomes a continuous stream of garbage. You can prove it with the allocation counter introduced in Span, Memory and slicing:

C# Class versus struct vectors per frame

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

That is why engines make vectors and colors structs, pre-size lists, reuse buffers and use object pools: create 200 bullets at load time and recycle them instead of creating and destroying them during play. Other common offenders are LINQ and string concatenation inside Update, lambdas that capture variables (see IL and the JIT), boxing value types into object, and foreach over an interface-typed collection.

Desktop applications

Desktop UI frameworks use a different loop: instead of redrawing continuously, they wait for events (a click, a key, a resize) and redraw what changed. The thread that runs this loop is the UI thread; touching a control from another thread is an error, which is why await in async code is so convenient in UI apps: after an await, you resume on the UI thread automatically.

The main choices for C# today:

Framework Platforms Style
WinForms Windows Drag-and-drop designer, event handlers. Old but still widely used for internal tools
WPF Windows XAML markup, data binding, MVVM. Rich styling
.NET MAUI Android, iOS, macOS, Windows XAML or C# markup, one codebase for mobile and desktop
Avalonia, Uno Platform Windows, macOS, Linux (and more) XAML-like, community-driven, strong Linux support
Blazor Hybrid Wraps web UI (HTML/Razor) in a native shell Reuses web skills

None of these run in our editor, since they need a window system. Here is the typical shape, read-only. A WPF screen is split into a view (markup) and code:

XML
<!-- Read-only: WPF MainWindow.xaml -->
<Window x:Class="Demo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Counter" Height="160" Width="260">
    <StackPanel Margin="16">
        <TextBlock Text="{Binding Count}" FontSize="32"/>
        <Button Content="Add one" Command="{Binding IncrementCommand}"/>
    </StackPanel>
</Window>
C#
// Read-only: WinForms version, event-handler style.
var button = new Button { Text = "Add one" };
var label = new Label { Text = "0" };
int count = 0;
button.Click += (sender, e) => label.Text = (++count).ToString();
Application.Run(new Form { Controls = { label, button } });

The XAML version contains no logic: {Binding Count} says "show the Count property of whatever object is my data context". That object is a view-model.

MVVM

Model-View-ViewModel separates three things: the model (your domain data and rules), the view (the screen), and the view-model (the screen's state and commands, with no references to controls). The view binds to the view-model through two small framework contracts, both in .NET's base library:

  • INotifyPropertyChanged: an event the view-model raises when a property changes, so the bound control updates itself.
  • ICommand: an object representing an action, with Execute and CanExecute (the framework disables the button when CanExecute returns false).

Because a view-model never touches controls, it is ordinary C# that you can unit test. The following runs here, with a PropertyChanged handler standing in for the data binding.

C# A view-model with INotifyPropertyChanged and ICommand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The view-model uses the events pattern and [CallerMemberName] (so you do not type property names as strings). The fourth click finds the command disabled, exactly as a bound button would be greyed out. In real projects the CommunityToolkit.Mvvm NuGet package generates this boilerplate with source generators (see Source Generators).

Keep game and UI code thin around a plain C# core. Put rules, calculations and state in ordinary classes with no engine or UI types; then you can test them like any other C# code, and reuse them in a console tool, a server or a different engine.

Other engines and where to go next

  • Godot 4 supports C# on modern .NET, so newer language features generally work.
  • MonoGame / FNA / Stride: code-first frameworks, closer to the "write your own loop" style shown above.
  • Unity has the largest community and learning material; remember its older C# version and runtime.

If you want a first project, build the loop and ECS above into a console simulation (falling objects, collisions), then port the logic to your engine of choice. The projects section of this tutorial starts with a command-line application that uses many of the same ideas.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why do many games run logic in fixed time steps with an accumulator?

    Fixed steps make physics and gameplay deterministic. The accumulator converts variable frame times into a whole number of equal logic steps.
  2. 2. How are Unity coroutines related to C# features?

    A coroutine is an IEnumerator method. The engine calls MoveNext on it at the right time, and each yield return says what to wait for.
  3. 3. What is the main idea of an entity-component system?

    ECS separates identity (entity), data (components) and behavior (systems), and stores data contiguously so loops are cache friendly.
  4. 4. Why is allocating a new object every frame in Update a problem in a game?

    At 60 frames per second you have about 16 ms per frame. Constant allocation leads to collections, and a long pause appears as a visible hitch.
  5. 5. What do INotifyPropertyChanged and ICommand give an MVVM view-model?

    The view-model raises PropertyChanged when state changes and exposes commands; the view binds to them. The view-model never references controls, so it stays testable.

Summary

  • Games and UIs are loop- or event-driven: a fixed-timestep accumulator keeps game logic deterministic, with rendering interpolating between steps.
  • Unity scripts are MonoBehaviour components with engine-called lifecycle methods; mind its older C# version, the overloaded == on engine objects and GC hitches.
  • Coroutines are iterators that an engine resumes; component models favor composition over inheritance.
  • ECS stores components as plain structs in contiguous arrays and processes them with systems for speed.
  • Avoid per-frame allocations: use structs, reuse buffers and pool objects.
  • Desktop frameworks (WinForms, WPF, MAUI, Avalonia) are event driven; MVVM with INotifyPropertyChanged and ICommand keeps logic out of the view and testable.

Next: Project: Command-Line To-Do App