Assembly Definitions & Tests
By default Unity compiles every script under Assets/ into one assembly, Assembly-CSharp.dll. Change one line anywhere and everything recompiles. As a project grows, that wait becomes the main drag on iteration. Assembly definitions split your code into separate assemblies with explicit dependencies, and they are also what the Unity Test Framework needs to find your tests.
Assembly definitions
- In a folder (for example
Assets/_Game/Scripts/Core), right-click and choose Create > Scripting > Assembly Definition (in some 6.x versions it's directly under Create). Name itGame.Core. - Every script in that folder and its subfolders now belongs to
Game.Core.dll, unless a subfolder has its own.asmdef. - In the asmdef's Inspector, add Assembly Definition References to other asmdefs it uses, such as
Unity.InputSystemorUnity.Cinemachine.
The file itself is small JSON:
{
"name": "Game.Gameplay",
"rootNamespace": "Game.Gameplay",
"references": [
"Game.Core",
"Unity.InputSystem",
"Unity.Cinemachine"
],
"includePlatforms": [],
"excludePlatforms": [],
"autoReferenced": true
}Rules worth knowing:
- References must form a DAG:
Gameplay → Coreis fine,Core → Gameplayas well would be a cycle and won't compile. That forces a cleaner architecture: low-level code can't depend on high-level code. - Code in
Assembly-CSharpcan see auto-referenced asmdefs, but an asmdef can't referenceAssembly-CSharp. Once you start, move all gameplay code into asmdefs. - An
Editorfolder inside an asmdef folder is not special anymore. Give editor code its own asmdef with Include Platforms: Editor only.
Only the changed assembly and the ones that depend on it recompile. The model shows the saving for a typical split:
using System;
using System.Collections.Generic;
using System.Linq;
// assembly -> (script count, references)
var asm = new Dictionary<string, (int Scripts, string[] Refs)>
{
["Game.Core"] = (60, new string[0]),
["Game.Data"] = (40, new[] { "Game.Core" }),
["Game.Gameplay"] = (220, new[] { "Game.Core", "Game.Data" }),
["Game.UI"] = (90, new[] { "Game.Core", "Game.Data" }),
["Game.Editor"] = (70, new[] { "Game.Core", "Game.Data", "Game.Gameplay" }),
};
int total = asm.Values.Sum(a => a.Scripts);
foreach (var changed in new[] { "Game.UI", "Game.Gameplay", "Game.Core" })
{
var dirty = new SortedSet<string> { changed };
bool grew = true;
while (grew) // everything that (transitively) references a dirty assembly
{
grew = false;
foreach (var (name, info) in asm)
if (!dirty.Contains(name) && info.Refs.Any(dirty.Contains)) { dirty.Add(name); grew = true; }
}
int scripts = dirty.Sum(d => asm[d].Scripts);
Console.WriteLine(quot;edit in {changed,-13}: recompile {scripts,3} of {total} scripts ({string.Join(", ", dirty)})");
}
Console.WriteLine(quot;without asmdefs: every edit recompiles all {total}");edit in Game.UI : recompile 90 of 480 scripts (Game.UI)
edit in Game.Gameplay: recompile 290 of 480 scripts (Game.Editor, Game.Gameplay)
edit in Game.Core : recompile 480 of 480 scripts (Game.Core, Game.Data, Game.Editor, Game.Gameplay, Game.UI)
without asmdefs: every edit recompiles all 480
Keep the low-level assemblies stable and small; most daily edits then happen in leaf assemblies and compile quickly. (Domain reload after compiling also costs time; Enter Play Mode Options can skip it when entering Play mode, if your code resets its static state.)
The Unity Test Framework
The Test Framework package (com.unity.test-framework) runs NUnit tests inside the editor. Open Window > General > Test Runner. There are two kinds:
| Edit Mode tests | Play Mode tests | |
|---|---|---|
| Run | in the editor, no Play mode | in Play mode (or in a player build) |
| Can use | plain C#, editor APIs | the full engine: frames, physics, coroutines |
| Speed | milliseconds | slower |
| Test asmdef | Include Platforms: Editor | all platforms |
- In the Test Runner, click Create Edit Mode Test Assembly Folder (the button name may differ slightly by version). It creates a folder with an asmdef that references NUnit.
- Add a reference to the assembly you want to test (
Game.Core). - Write tests:
using NUnit.Framework;
using System.Collections;
using UnityEngine;
using UnityEngine.TestTools;
public class WalletTests // Edit Mode: plain C# logic
{
[Test]
public void Spending_more_than_balance_fails()
{
var wallet = new Wallet(10);
Assert.IsFalse(wallet.TrySpend(15));
Assert.AreEqual(10, wallet.Balance);
}
}
public class FallingTests // Play Mode: needs frames and physics
{
[UnityTest]
public IEnumerator Rigidbody_falls_under_gravity()
{
var go = GameObject.CreatePrimitive(PrimitiveType.Cube);
go.AddComponent<Rigidbody>();
float startY = go.transform.position.y;
yield return new WaitForSeconds(0.5f);
Assert.Less(go.transform.position.y, startY);
Object.Destroy(go);
}
}The best test targets are the plain C# classes your MonoBehaviours delegate to: the wallet, inventory rules, damage formulas, the state machine, save migration. Those are exactly the parts this course models in runnable C#. Keep MonoBehaviours thin and they hardly need tests.
Run tests from the command line in CI with -runTests -testPlatform EditMode -testResults results.xml (plus -batchmode -projectPath <path>).
Test yourself
You edit a script in Game.UI, which nothing references. What recompiles?
- Every assembly
- Only Game.UI
- Game.Core
- Assembly-CSharp and Game.Core
Which test attribute lets a test wait for frames with yield return?
[Test][UnityTest][SetUp][TestCase]
Why can't Game.Core reference Game.Gameplay if Game.Gameplay references Game.Core?
- Names must be alphabetical
- Assembly references must not form a cycle
- Core assemblies can't reference anything
- Only editor assemblies can reference others