In Unity, [SerializeField]
attribute is used to make the private
variables accessible within the Unity editor without making them public
. It helps maintain GameObjects
.
[SerializeField]
Given below is a detailed explanation on using [SerializeField]
.
Define the private variable which you want to make visible in the editor.
Place the [SerializeField]
above the variable declaration.
Save the C# script
The variable appears in the Unity editor.
You can modify the value of the variable here.
[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 int
is declared and initialized with a value of 10
here.
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.
[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
value
variable is not accessible as it is used without[SerializeField]
.
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