Consider this Unity C# script attached to a GameObject:
using UnityEngine;
public class TestScript : MonoBehaviour {
public int publicValue = 5;
[SerializeField] private int serializedValue = 10;
void Start() {
Debug.Log(publicValue);
Debug.Log(serializedValue);
}
}What will be printed in the Unity Console when the game starts?
using UnityEngine; public class TestScript : MonoBehaviour { public int publicValue = 5; [SerializeField] private int serializedValue = 10; void Start() { Debug.Log(publicValue); Debug.Log(serializedValue); } }
Remember that SerializeField makes private fields visible in the Inspector and keeps their values.
The publicValue is public, so it can be accessed and printed directly. The serializedValue is private but marked with [SerializeField], so Unity serializes it and keeps its value. Both print their assigned values.
In Unity, why would a developer use [SerializeField] on a private field instead of making the field public?
Think about encapsulation and editing values in the Unity Editor.
[SerializeField] allows private fields to be shown and edited in the Unity Inspector without exposing them publicly to other scripts. This helps keep code encapsulated while allowing designers to tweak values.
Look at this Unity script:
using UnityEngine;
public class Player : MonoBehaviour {
private int health = 100;
[SerializeField] private int mana;
void Start() {
Debug.Log(health);
Debug.Log(mana);
}
}When attached to a GameObject, the mana field does not show in the Inspector. What is the most likely reason?
Unity requires script file names to match class names exactly.
If the script file name does not match the class name, Unity will not compile the script properly, and serialized fields won't show in the Inspector. This is a common cause of private serialized fields not appearing.
Which of the following Unity C# code snippets correctly serializes a private integer field so it appears in the Inspector?
Look at the correct order of attributes and access modifiers in C#.
The attribute [SerializeField] must come before the access modifier and type declaration. Option D is the correct syntax.
You are designing a Unity game and want to store a player's maximum health. You want this value to be editable in the Inspector but not accessible or modifiable by other scripts directly. Which declaration is best?
Think about encapsulation and Inspector visibility.
Option B keeps the field private so other scripts cannot access it directly, but [SerializeField] makes it editable in the Inspector. This balances encapsulation and usability.