When getting reference to a SerializedProperty (using FindProperty or FindPropertyRelative) in a Unity Editor, you may encounter a null reference exception. I’ve found this is almost always due to a few basic causes.
Property is Not Public or Serialized
Sometimes it’s a simple matter of forgetting to mark a field public. If you want to keep the field private, but still need it edited in the inspector then add [SerializeField] before the property.
Example:
[SerializeField] bool showCameraList;
Type is Not Serializable
The type of the property must be serializable. For custom enums, structs, or classes, this can just mean adding [System.Serializable] before the definition.
Example:
[System.Serializable]
public class ScreenshotScript : MonoBehaviour
There are special cases where this may not work. Unity does not serialize multilevel types such as multi-dimensional arrays or dictionaries. Static, const, or readonly fields will also not be serialized.
Property is Spelled Wrong
You may just have a typo. Double check you’ve got the spelling and capitalization right.
Summary
That’s about it! I hope this article saves you a bit of extra time.
While researching this article, I found Unity’s more comprehensive article on serialization. Check it out if things still aren’t working.
Be First to Comment