Performance: Public vs SerializeField
This concept affects the memory usage and serialization performance during game loading and editor interaction in Unity.
[SerializeField] private int health = 100;
public int health = 100;
| Pattern | Serialized Data Size | Memory Usage | Encapsulation | Verdict |
|---|---|---|---|---|
| Public fields | Larger (all public fields serialized) | Higher (more data loaded) | Low (fields accessible everywhere) | [X] Bad |
| [SerializeField] private fields | Smaller (only marked fields serialized) | Lower (less data loaded) | High (fields encapsulated) | [OK] Good |
public variable and a [SerializeField] private variable in Unity?public variable behaviorpublic variable is accessible by all scripts and also visible in the Unity Inspector for editing.[SerializeField] with private[SerializeField] private variable is hidden from other scripts but still visible and editable in the Inspector.public variables are accessible by other scripts and visible in the Inspector, while [SerializeField] private variables are only visible in the Inspector but not accessible by other scripts. -> Option Apublic and [SerializeField] private [OK][SerializeField] attribute must be placed before the variable declaration.[SerializeField] private int score; to make a private variable visible in Inspector.public class Player : MonoBehaviour {
[SerializeField] private int health = 100;
public int score = 0;
void Start() {
Debug.Log(health);
Debug.Log(score);
}
}
What will be printed in the Unity Console when the game starts?health is serialized and initialized to 100, so it is accessible inside the class and prints 100. The public variable score is initialized to 0 and prints 0.Debug.Log(health) and Debug.Log(score) print their current values: 100 and 0 respectively.public class Enemy : MonoBehaviour {
[SerializeField] private int damage = 10;
}
But in the Inspector, the damage value stays at 0 even after you press Play. What is the likely problem?damage is 0, so even though code initializes it to 10, the Inspector value overrides it.speed editable in the Unity Inspector but prevent other scripts from modifying it directly. Which is the best way to declare it?[SerializeField] with private, making it editable in Inspector but hidden from other scripts. public float speed { get; private set; } uses a public property with private setter, which is not visible in Inspector by default.Pass the test and this pattern moves unknown