What is "SerializeField" in Unity?
In Unity, [SerializeField] attribute is used to make the private variables accessible within the Unity editor without making them public. It helps maintain GameObjects.
How to use [SerializeField]
Given below is a detailed explanation on using [SerializeField].
Declare the variable
Define the private variable which you want to make visible in the editor.
Apply the attribute
Place the
[SerializeField]above the variable declaration.
Adjust the value in editor
Save the C# script
The variable appears in the Unity editor.
You can modify the value of the variable here.
Syntax
[SerializeField]// The value can be modified in the editor now.private int value = 10;
Here,
Line 1: It uses the
[SerializeField]attribute before declaring a private variable.Line 2: A private variable of type
intis declared and initialized with a value of10here.It is the basic syntax of declaring a private variable to make it accessible in the editor.
Note:
You can use the
[SerializeField]attribute with the public variables, but it is redundant.
Public variables are already visible and editable in the editor.
Adding the
[SerializeField]will not change the behavior of the variable.You can use
[SerializeField]attribute with the private variables to make them visible in the editor.
Making the variable type private ensures encapsulation.
Why use [SerializeField]?
The [SerializeField] in Unity is a helpful tool for various reasons explained below.
Visibility: You can inspect and modify the private variables at runtime. It allows you to quickly test the values and check the behavior of the objects.
Tweak values: Certain values need adjustment in the debugging process. Using
[SerializeField]allows you to modify the values directly in the editor, even while the game is running. It allows you to see the live effects of changes you make.Maintain encapsulation: By making the variables private, you ensure that it can only be modified within its class. It prevents the modifications of the variables from other parts/scripts of your code, maintaining encapsulation.
Note: In slide 2, the
valuevariable is not accessible as it is used without[SerializeField].
Sample project
In the sample project, the changeText variable is set to use [SerializeField] and is declared private. Using [SerializeField] allows you to change the text during the runtime as shown below.
Note: Notice the inspector in the right side of the video to see live changes.
Free Resources