Skip to content

Redundant SerializeField attribute

Matt Ellis edited this page Feb 19, 2019 · 7 revisions

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 is static or readonly, or when the field's class isn't serialisable, either because it doesn't derive from a Unity base class such as MonoBehaviour, 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.

Remarks

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.

Clone this wiki locally