|
| 1 | + |
| 2 | + |
| 3 | +# Attributes |
| 4 | + |
| 5 | +You may be familiar with the use of [SerializeField] for exposing variables in the unity editor inspector as opposed to making fields public. This is only one of many useful attributes you can attach to a field ("Range" may be another one of interest?) |
| 6 | + |
| 7 | +Unity allows us as developers to greatly extend the editor with custom editor scripts (CustomEditor and PropertyDrawer), With that, they also allow us to define custom attributes, and add specifications for how fields marked with said attributes are drawn in the editor. |
| 8 | + |
| 9 | +Currently, we have the following attributes which modifies how the fields marked with them are drawn: |
| 10 | + |
| 11 | +---- |
| 12 | + |
| 13 | +## PrefabOnly |
| 14 | + |
| 15 | +Can be put on any `GameObject` field or component fields (i.e. fields of classes inheriting from the base class `Component` - i.e. all built-in components, as well as custom `MonoBehaviour`) |
| 16 | + |
| 17 | +The attribute disallows references to in-scene gameobjects/components |
| 18 | + |
| 19 | +Example: |
| 20 | + |
| 21 | +```cs |
| 22 | +[PrefabOnly, SerializeField] |
| 23 | +private GameObject somePrefab; |
| 24 | + |
| 25 | +// Note: usage of this is scary, and should only be used in a "read-only" context or in |
| 26 | +// editor-related contexts. Changing it would change the prefab's Rigidbody. |
| 27 | +[PrefabOnly] |
| 28 | +public Rigidbody someRigidbodyOfAPrefab; |
| 29 | +``` |
| 30 | + |
| 31 | +## Uneditable |
| 32 | + |
| 33 | +Can be put on any field (though only useful on serialized fields - as others aren't editable through the editor anyways) |
| 34 | + |
| 35 | +The attribute allows insight in the field, but disallows changing the field from editor. Can be useful for displaying debug info, or simply for disallowing edits while keeping the field serialized. |
| 36 | + |
| 37 | +Example: |
| 38 | + |
| 39 | +```cs |
| 40 | +[Uneditable, SerializeField] |
| 41 | +private GameObject someObjectReferenceThatCannotBeChangedInEditor; |
| 42 | + |
| 43 | +[Uneditable] |
| 44 | +public float someFloatSetInternally; |
| 45 | +``` |
| 46 | + |
| 47 | +## LabelAs |
| 48 | + |
| 49 | +Can be put on any field (though only useful on serialized fields - as others aren't labelled in the editor anyways) |
| 50 | + |
| 51 | +The attribute allows "rebranding" a variable as it is shown in the editor. |
| 52 | + |
| 53 | +Example: |
| 54 | + |
| 55 | +```cs |
| 56 | +[LabelAs("Some Name That Makes Sense In Editor Context"), SerializeField] |
| 57 | +private string someVariableNameThatMakesSenseInScriptingContext; |
| 58 | +``` |
0 commit comments