-
Notifications
You must be signed in to change notification settings - Fork 134
Redundant SerializeField attribute
This inspection will highlight the [SerializeField]
attribute as redundant in the following conditions:
- If a field has both
[SerializeField]
and[NonSerialized]
attributes, the[NonSeralized]
attribute takes precedence and Unity will ignore the[SerializeField]
attribute. If both attributes are applied to a field, the[SerializeField]
attribute is marked as redundant. - Starting with Rider/ReSharper 2018.2, this inspection will mark a
[SerializeField]
attribute as redundant if it is applied to a field that can't be serialised, such as when the field isstatic
orreadonly
, or when the field's class isn't serialisable, either because it doesn't derive from a Unity base class such asMonoBehaviour
, or because it's a plain .NET class that does not have the[System.Serializable]
attribute.
This inspection also provides an Alt+Enter quick fix to remove the redundant attribute. For plain .NET classes, it also provides a quick fix to mark the class with the [System.Serializable]
attribute.
Note that Unity will serialise a field marked with [SerializeField]
on a class that does NOT have [System.Serializable]
when using explicit serialisation APIs such as JsonUtility.ToJson
. However, it will not serialise the field if the same class is used for implicit serialisation inside a Unity derived class, such as a field inside a MonoBehaviour
based class. This means it is possible to get an incorrect redundant attribute warning when the class is only used for explicit serialisation.
This is considered an edge case - it is not viable to detect when the class is only used for explicit serialisation, and it is more important to warn when implicit serialisation is likely to fail. The workaround for the edge case is to use the quick fix to add the [System.Serializable]
attribute to the class.
See also the Unity documentation on SerializeField
.