Class SortingLayerFieldAttribute
Marks an int field so the Inspector renders it as a sorting layer selection
dropdown instead of a raw integer input, storing the selected sorting layer's
persistent ID rather than its transient index.
Inherited Members
Namespace: Scylla.Core.Attributes
Assembly: ScyllaCore.dll
Syntax
[AttributeUsage(AttributeTargets.Field)]
public sealed class SortingLayerFieldAttribute : PropertyAttribute
Remarks
When this attribute is applied to a serialized int field, the custom
property drawer (SortingLayerFieldDrawer) replaces the default integer field
with a popup listing every sorting layer currently defined in the project's Tags
and Layers settings. The backing field stores the sorting layer's ID
(as returned by SortingLayer.id), which is a stable value that does not
change when layers are reordered in the editor.
ID vs index: Unity exposes two ways to identify a sorting layer - its
index (position in the layer list, which can change as layers are added,
removed, or reordered) and its ID (an internal hash that remains constant
for the lifetime of the layer). This attribute stores the ID, matching the value
expected by SpriteRenderer.sortingLayerID,
ParticleSystemRenderer.sortingLayerID, and similar Unity component
properties. Pass the stored value directly to those properties without any
conversion.
Using this attribute instead of a raw int field provides two concrete
benefits:
- It prevents hardcoded sorting layer IDs that become stale when layers are renamed or recreated in the Project Settings.
- It makes the Inspector self-documenting: designers and engineers see human-readable sorting layer names rather than opaque integer IDs.
Field type requirement: The decorated field must be of type int. If
the attribute is placed on any other type, the Inspector will display a red error
help box instead of the dropdown, and the field will not be editable until the
type is corrected.
The drawer caches sorting layer data and only rebuilds the cache when the number or composition of sorting layers changes, keeping Inspector rendering efficient even in scenes with many components.
public class SpriteController : MonoBehaviour
{
/* Dropdown showing all sorting layers; stores the sorting layer ID as int. */
[SortingLayerField]
[SerializeField] private int _backgroundSortingLayer;
[SortingLayerField]
[SerializeField] private int _foregroundSortingLayer;
private SpriteRenderer _renderer;
private void Start()
{
_renderer = GetComponent<SpriteRenderer>();
/* Assign the stored sorting layer ID directly to the SpriteRenderer. */
_renderer.sortingLayerID = _backgroundSortingLayer;
}
}