Quick answer: Most Unity errors belong to one of four groups: a reference that is null, unassigned or destroyed; a collection indexed or modified wrongly; Unity API called at the wrong time or on the wrong thread; and scripts or native libraries Unity cannot compile or load. Read the first line for the error type and the stack trace for the line in your own code, then apply the matching fix below.
The Unity Console repeats itself. A small set of messages accounts for most of what a project throws, from the first tutorial to a shipped game, and each one has a short list of real causes. This page covers twelve of them for Unity 6 and 2022 LTS. Every entry gives the message exactly as Unity prints it, the reason it fires, the shortest fix that is actually correct, and a link to a longer guide. A table at the top lets you jump straight to yours, and the last section explains which of these change or only appear in a player build.
- Summary table
- 1. NullReferenceException
- 2. MissingReferenceException
- 3. UnassignedReferenceException
- 4. MissingComponentException
- 5. IndexOutOfRangeException and ArgumentOutOfRangeException
- 6. InvalidOperationException: Collection was modified
- 7. “can only be called from the main thread”
- 8. StackOverflowException
- 9. “The referenced script (Unknown) on this Behaviour is missing!”
- 10. “All compiler errors have to be fixed before you can enter playmode!”
- 11. error CS1061 and error CS0246
- 12. DllNotFoundException
- Which of these change or only appear in player builds
- Collecting these from players
- Related guides
- Frequently asked questions
Summary table
| Error | Cause in one line | First thing to check |
|---|---|---|
| NullReferenceException | You used a variable that holds nothing | Which reference on the reported line is null |
| MissingReferenceException | You used an object after it was destroyed | Events, coroutines and lists that still hold it |
| UnassignedReferenceException | An Inspector slot was left empty | The field named in the message, on every object with that script |
| MissingComponentException | GetComponent found nothing and you used the result | Whether the component is on a child, a parent or is the 2D type |
| IndexOutOfRangeException / ArgumentOutOfRangeException | Index below zero or past the end | The index value against Length or Count |
| InvalidOperationException: Collection was modified | A list changed during a foreach over it | What the loop body calls that adds or removes |
| can only be called from the main thread | Unity API in a field initializer or on another thread | The stack trace: a .ctor frame, or System.Threading |
| StackOverflowException | Recursion that never ends | Properties that return themselves |
| The referenced script (Unknown) on this Behaviour is missing! | A component points at a script Unity cannot find | Deleted, moved or renamed scripts and their .meta files |
| All compiler errors have to be fixed before you can enter playmode! | At least one script does not compile | The first red error CS line in the Console |
| error CS1061 / CS0246 | A member or type name the compiler does not know | Spelling, the variable’s type, missing using |
| DllNotFoundException | A native plug-in failed to load | The plug-in’s platform and CPU import settings |
Every runtime entry in the Console has the same anatomy: the exception type, a message, then a stack trace. The first trace line under Assets/ is the line of your code to open.
1. NullReferenceException
NullReferenceException: Object reference not set to an instance of an object
PlayerController.Update () (at Assets/Scripts/PlayerController.cs:23)
You accessed a member of a variable that holds no object. The message never says which variable, so the line number is everything: look at each thing before a dot on line 23. The usual sources are a GetComponent or Find that returned nothing, a field assigned in another script’s Start that has not run yet, and an Inspector slot nobody filled.
void Awake()
{
health = GetComponent<Health>();
if (health == null)
Debug.LogError($"{name} has no Health component", this);
}
Assign in Awake, use in Start or later, and report a missing dependency by name instead of sprinkling null checks that hide it. Full guide: how to fix Unity’s NullReferenceException.
2. MissingReferenceException
MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
The variable is not empty. It points at an object that was removed by Destroy or a scene unload, and something kept using it: an event subscription, a coroutine, an async method, a list. The operators ?., ?? and is null do not detect destroyed objects; only == null does.
void OnEnable() { player.HealthChanged += OnHealthChanged; }
void OnDisable() { player.HealthChanged -= OnHealthChanged; }
An unsubscribed event is the fix more often than anything else. Full guide: MissingReferenceException: the object has been destroyed.
3. UnassignedReferenceException
UnassignedReferenceException: The variable target of CameraFollow has not been assigned.
You probably need to assign the target variable of the CameraFollow script in the inspector.
A public or [SerializeField] field of a Unity type was left as None in the Inspector, and the script used it. The message names the field and the script (some Unity versions put the script name in quotes). It often comes from a second copy of the script on an object you forgot about, or from a prefab whose scene reference could not be saved.
[SerializeField] Transform target;
void OnValidate()
{
if (target == null)
Debug.LogWarning($"{name}: CameraFollow.target is not assigned", this);
}
Drag the object into the slot; the OnValidate check warns you in the editor before you press Play. Full guide: UnassignedReferenceException.
4. MissingComponentException
MissingComponentException: There is no 'Rigidbody' attached to the "Player" game object, but a script is trying to access it.
You probably need to add a Rigidbody to the game object "Player". Or your script needs to check if the component is attached before using it.
GetComponent searched one GameObject, found no component of that type, and the script used the result. Often the component exists somewhere else: on a child or parent, or as Rigidbody2D when the script asks for Rigidbody.
[RequireComponent(typeof(Rigidbody))]
public class PlayerMotor : MonoBehaviour
{
Rigidbody body;
void Awake() { body = GetComponent<Rigidbody>(); }
}
[RequireComponent] adds the component whenever the script is added. Use GetComponentInParent or GetComponentInChildren when it lives elsewhere, and TryGetComponent when it is optional. Full guide: MissingComponentException: there is no component attached.
5. IndexOutOfRangeException and ArgumentOutOfRangeException
IndexOutOfRangeException: Index was outside the bounds of the array.
ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
The first is thrown by arrays, the second by List<T>. Both mean the index was negative or not less than the size. The repeat offenders are <= where < was meant, indexing an empty collection, and an index saved before the collection shrank.
if (spawnPoints.Length == 0) return;
// For ints the upper bound of Random.Range is exclusive, so Length is correct
Transform point = spawnPoints[Random.Range(0, spawnPoints.Length)];
Log the index and the size on the line before the access and the cause is usually obvious. Full guide: Index was outside the bounds of the array.
6. InvalidOperationException: Collection was modified
InvalidOperationException: Collection was modified; enumeration operation may not execute.
A List or Dictionary was changed while a foreach was walking it. The stack trace points at the foreach line, not at the code that changed the collection, and that code is frequently indirect: an OnDisable that unregisters from a manager while the manager is looping.
for (int i = enemies.Count - 1; i >= 0; i--)
{
if (enemies[i].IsDead)
enemies.RemoveAt(i);
}
Loop backwards by index, or call enemies.RemoveAll(e => e.IsDead). In Unity this also applies to removing from a dictionary inside foreach, which current .NET permits and Unity’s runtime does not. Full guide: Collection was modified; enumeration operation may not execute.
7. “can only be called from the main thread”
UnityException: get_transform can only be called from the main thread.
Constructors and field initializers will be executed from the loading thread when loading a scene.
Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.
The first word changes with the API (Find, SetActive, get_persistentDataPath). There are two causes with one message. Either a Unity call sits in a MonoBehaviour field initializer or constructor, or it runs on a background thread: inside Task.Run, a socket callback, a timer.
// Field initializer: move it
GameObject player;
void Awake() { player = GameObject.Find("Player"); }
// Background work: come back to the main thread before touching Unity
var data = await Task.Run(() => LevelParser.Parse(text));
titleLabel.text = data.title;
Full guide, including a dispatcher and Awaitable.MainThreadAsync() for Unity 6: can only be called from the main thread.
8. StackOverflowException
StackOverflowException: The requested operation caused a stack overflow.
A method called itself, directly or through a cycle, until the call stack ran out. In Unity code the classic is a property whose getter or setter uses the property’s own name. Others are an event handler that raises the event it is handling, and a prefab that instantiates itself in Awake. The editor may freeze or close before it manages to print the message.
// Broken: the property calls itself
public int Health { get { return Health; } set { Health = value; } }
// Fixed: a separate backing field
int health;
public int Health { get => health; set => health = Mathf.Max(0, value); }
The stack trace shows the same one or two methods repeating; those are the cycle. Full guide: StackOverflowException in Unity.
9. “The referenced script (Unknown) on this Behaviour is missing!”
The referenced script (Unknown) on this Behaviour is missing!
The referenced script on this Behaviour (Game Object 'Enemy') is missing!
This is a warning, not an exception. A component slot on a GameObject or prefab refers to a script asset Unity cannot resolve. The script was deleted, or it was moved or renamed outside Unity so its .meta file and GUID were lost, or it no longer compiles into the build. The component shows as “Missing (Mono Script)” in the Inspector and does nothing.
// Editor script: strip dead components from the selected objects
[MenuItem("Tools/Remove Missing Scripts From Selection")]
static void RemoveMissing()
{
foreach (GameObject go in Selection.gameObjects)
GameObjectUtility.RemoveMonoBehavioursWithMissingScript(go);
}
If the script still exists, drag it back into the empty slot instead, and fix the prefab asset, not only the scene instance. Move and rename scripts inside the editor so the .meta file travels with them. Full guides: the referenced script is missing and missing .meta files.
10. “All compiler errors have to be fixed before you can enter playmode!”
All compiler errors have to be fixed before you can enter playmode!
This line is a consequence. Somewhere in the project a script does not compile, so Unity cannot build the script assemblies and refuses to enter play mode. The real errors are the red entries above it, in this format:
Assets/Scripts/Enemy.cs(31,9): error CS1002: ; expected
That reads as file, then line 31, column 9, then the C# error code. Clear the Console, let Unity recompile, and fix the first error; later ones are often side effects of it. A script inside an asset or package you just imported counts as much as your own. Full guide: All compiler errors have to be fixed.
11. error CS1061 and error CS0246
Assets/Scripts/Player.cs(14,12): error CS1061: 'Rigidbody' does not contain a definition for 'velocty' and no accessible extension method 'velocty' accepting a first argument of type 'Rigidbody' could be found (are you missing a using directive or an assembly reference?)
Assets/Scripts/Hud.cs(7,12): error CS0246: The type or namespace name 'TextMeshProUGUI' could not be found (are you missing a using directive or an assembly reference?)
CS1061: the type on the left of the dot has no member with that name. It is a typo, wrong capitalization (getComponent), a call on the wrong type (AddForce on a GameObject instead of its Rigidbody), or an API renamed in an upgrade. CS0246: the compiler does not know the type at all, because a using line is missing, the package is not installed, or an assembly definition lacks a reference.
using TMPro; // CS0246: bring the namespace in
GetComponent<Rigidbody>().AddForce(Vector3.up); // CS1061: call it on the component
Full guides: error CS1061 and the type or namespace could not be found.
12. DllNotFoundException
DllNotFoundException: MyPlugin assembly:<unknown assembly> type:<unknown type> member:(null)
DllNotFoundException: Unable to load DLL 'MyPlugin'. Tried the load the following dynamic libraries: Unable to load dynamic library 'MyPlugin' because of 'Failed to open the requested dynamic library (0x06000000) dlerror() = dlopen failed: library "MyPlugin" not found
The first form comes from the Mono backend, the second from IL2CPP (the typo is Unity’s). A method marked [DllImport] was called and the native library could not be loaded on this machine. Either there is no binary for this platform and CPU architecture, the plug-in’s import settings exclude it from this build, or a library it depends on is missing.
[DllImport("MyPlugin")] // no "lib" prefix, no file extension
static extern int my_plugin_init();
Select the plug-in file and check the platform and CPU boxes in the Inspector for every target you build. Full guide: DllNotFoundException: Unable to load DLL.
Which of these change or only appear in player builds
The editor is not the game. Several entries above behave differently once you build.
- Three exceptions become one. MissingReferenceException, UnassignedReferenceException and MissingComponentException are editor diagnostics. A player build skips the extra bookkeeping and throws a plain
NullReferenceExceptionfor all three, with no type, field or object name. A build that passes through a menu and several scene loads also reaches states you never reach when you press Play in a gameplay scene, which is when references to destroyed scene objects show up. - Native plug-ins are per platform. The editor loads the desktop binary for your development machine. An Android, iOS or Linux build needs its own library for each CPU architecture, so a
DllNotFoundExceptioncan be impossible to reproduce in the editor. - Stripped code. With IL2CPP and a higher Managed Stripping Level, code that is reached only through reflection (serializers, dependency injection) can be removed from the build. Preserve it with a
link.xmlfile or the[Preserve]attribute. See IL2CPP stripping removes needed types and the related ExecutionEngineException for missing AOT code. - Editor-only scripts. A MonoBehaviour in an
Editorfolder, or one that uses theUnityEditornamespace outside#if UNITY_EDITOR, works in play mode and then either fails the build with CS0246 or leaves a missing script behind. - Threading checks are relaxed. Unity’s manual says a release build runs main-thread violations in loading code “without errors” but with possible crashes, so the exception you ignored in the editor may not exist to warn you later.
To see what a build throws, read Player.log. On Windows it is at %USERPROFILE%\AppData\LocalLow\CompanyName\ProductName\Player.log; the Console window menu also has Open Player Log. Make a development build to keep file names and line numbers, and for IL2CPP release builds set IL2CPP Stacktrace Information in Player Settings to include them.
Collecting these from players
Everything above assumes you can see the Console. For players you cannot, and “it broke” is all they will tell you. The Bugnet Unity SDK is one C# file that listens to Application.logMessageReceived and files each exception, error or failed assert as a report with the stack trace, recent log lines, platform, OS version, CPU, GPU, RAM and game version, once per distinct message per session. Identical titles stack into a single entry with an occurrence count. It covers the runtime errors in this list. It does not see the missing-script message, which is a warning, and compiler errors never reach a build. A DllNotFoundException is captured when the managed call fails, but a game that cannot start at all has nothing running to report it. The free plan covers one project and up to 100 bug reports in total. Start with the getting started guide.
Related guides
- How to Fix “MissingReferenceException: The object of type ‘GameObject’ has been destroyed” in Unity
- How to Fix “MissingComponentException: There is no ‘Rigidbody’ attached to the game object” in Unity
- How to Fix “InvalidOperationException: Collection was modified; enumeration operation may not execute” in Unity
- How to Fix “can only be called from the main thread” Errors in Unity
- Understanding Stack Traces in Unity Crash Logs
Frequently asked questions
What is the most common error in Unity?
NullReferenceException is the one most Unity developers meet first and most often. It means a script used a variable that holds no object, typically an Inspector field that was never assigned, a GetComponent call that found nothing, or an object that another script has not set up yet.
Why does my Unity game work in the editor but throw errors in the build?
Builds differ from play mode in several ways. Editor-only exception types turn into plain NullReferenceException, native plug-ins must exist for the target platform, IL2CPP can strip code used only through reflection, and scripts in Editor folders are not included. Read Player.log from a development build to see the actual error.
How do I read a Unity error message?
The first line gives the exception type and a message. Below it is the stack trace, one method call per line, newest first. Find the first line that mentions a file under Assets, with a line number in brackets, and open that line. Double-clicking the Console entry does this for you.
What is the difference between NullReferenceException and MissingReferenceException?
NullReferenceException means the variable never pointed at an object, or holds a real null. MissingReferenceException means it pointed at a real Unity object that has since been destroyed. The second one is editor-only; in a player build both appear as NullReferenceException.
Where is the error log for a built Unity game?
The player writes Player.log. On Windows it is under the user’s AppData LocalLow folder, in a folder named after the company and product set in Player Settings. On Android the same output goes to logcat. The editor’s Console window menu has an Open Player Log command for local builds.
Three of these twelve errors exist only in the editor. If a build throws a NullReferenceException you have never seen in play mode, check for a destroyed object, an empty Inspector slot or a missing component first.