🤔 Unity, huh, how?

🤔

MissingReferenceException

A MissingReferenceException is a type of NullReferenceException where a Unity Object field was previously assigned to, and the contents have been deleted or become invalid.

It can also occur when using GetComponent in cases where the component was not present.

Resolution

First, read the error message and understand what types and variables it's talking about.

information

In some cases selecting the error message in the Unity Console will ping the object that threw it.

Then choose the type of MissingReferenceException that relates to your message:

MissingReferenceException: The variable Foo of Bar doesn't exist anymore.

Re-assign a value to the field mentioned (Foo) to all instances of the script (Bar) via the Inspector.

Search the scene for all instances of the caller and check all results (t:ExampleComponent for example) if it appears assigned.

MissingReferenceException: There is no 'Foo' attached to the "Bar" game object.

information

If you have already serialized and assigned the variable in the inspector you do not need to assign it in code.
Remove the GetComponent and the issue will be resolved.

Check that the mentioned component (Foo) is attached to all game object instances named (Bar) in the scene.

Alternatively, if you're using GetComponent and want to check if the component was correctly found, use TryGetComponent instead:

if (TryGetComponent(out Foo foo))
{
    // Foo has been found correctly.
}

Invalid GetComponent usage

warning

This can also occur when trying to retrieve something that isn't a Component using the GetComponent functions.

For example, There is no 'GameObject' attached to the "Example" game object, is caused by GetComponent<GameObject>(). To get a GameObject from a component Unity exposes the gameObject property.

MissingReferenceException: The object of type 'Foo' has been destroyed but you are still trying to access it.

You destroyed an object (an instance of Foo), and attempted to read from a variable that referenced it.

Read the stack trace, and find what call threw the exception, and figure out whether to correctly reference an existing object, or to check if the object is destroyed.

To check if an Object was destroyed in Unity, check if it's null:

if (foo != null)
{
    // foo is assigned and has not been destroyed.
}

To find more troubleshooting steps, read through the NullReferenceException guide.