UnassignedReferenceException: The variable has not been assigned
UnassignedReferenceException: The variable X of Y has not been assigned. You probably need to assign the X variable of the Y script in the inspector.
A field that Unity serializes, a public field or one marked [SerializeField], is empty in the Inspector and your code used it. Unity names the exact variable and script for you.
Read the Console line first
The message reads: the variable X of Y. X is the field name and Y is the script. Type t:Y into the Hierarchy search to list every object that has the script.
Common causes
The slot shows None in the Inspector
Select the object, find the script, and drag the right object or asset into the empty field.
Only some copies are missing it
The prefab has the reference but one instance in the scene overrides it with nothing, or a copy was made before the field was added. Check every instance, or apply the field on the prefab.
The script is on a second object you forgot about
The same script is attached twice, and the second copy has empty fields. Search the Hierarchy with t:YourScript to find every copy.
The fix
void OnValidate()
{
if (target == null)
Debug.LogWarning($"{name}: assign Target in the Inspector", this);
}Stop it coming back
OnValidate runs in the Editor whenever the Inspector changes, so a warning there catches an empty field before you press Play.
Questions
- Why does the Editor say Unassigned when a build says NullReferenceException?
- In the Editor, Unity fills empty serialized object fields with a placeholder that throws this more helpful exception, naming the variable and the script. A player build has no placeholder, so the same empty field fails as a plain NullReferenceException. Fix it the same way in both: assign the slot.
- I assigned it, but the error still appears. What now?
- Another copy of the script has the slot empty: a second object, an instance of a prefab that overrides the field, or an object spawned at runtime. Type
t:YourScriptin the Hierarchy search box to list every object with the script and check each one. - Can Unity warn me before I press Play?
- Yes. Check the field in
OnValidate, which runs in the Editor whenever you change a value, and log a warning with the object as context, for exampleif (target == null) Debug.LogWarning($"{name}: target is empty", this);.
Scripts that avoid it
Related errors
Got a different error? Paste it into the error lookup.