How to fix object reference not set to an instance of an Object error in unity C#

  "Object reference not set to an instance of an object"  is a error which occurs when we try to access a script or gameObject which is not assigned or initialized.

object reference not set to an instance of an Object error in unity


Some of common reasons for this error are following:

  • We forget to drag and drop gameObject or component in inspector in unity editor or don't assign.
  • We don't assign reference to script or component by code
  • Script or component that we want to access is not present in scene.
  • Script or component is disabled
  • May be script or gameObject is destroyed or deleted.

If want to fix this issue we have to identify which part of code is referencing this null exception and then assign valid gameObject or script to variable in script.

Here a few ways so we use in order to identify which part of code have null reference:

Code :
if(object == null)
{
    // script or object is not assigned
}
We also need to check if gameObject is deleted or destroyed in runtime by using if statement and checking if this variable is null or not:
Code :
if(object == null)
{
    // script or object is destroyed or deleted
}
We also need to check gameObject is enabled or not in game because if gameObject is disabled then this any script attached with it will not work.
Code :
if(object.enabled == false)
{
    // script or gameObject is disabled
}
By using these some common code practice you can lower these exception.


Comments