In this lesson, you will learn how to safely evolve your data structures without breaking your existing Prefabs and ScriptableObjects.
When you modify a script—such as renaming a variable or changing a data type—Unity’s serialization system can struggle to map the old data to the new structure. If you simply delete an old field and add a new one, all instances of that asset in your project will lose their previously assigned values. To prevent this, we use a "migration strategy" inside the OnValidate method or by implementing ISerializationCallbackReceiver.
The Migration Pattern
The most robust approach is to keep the old variable temporarily, mark it as [SerializeField, HideInInspector], and transfer its data to the new variable during the first load.
Consider a scenario where you want to rename public int health to public int maxHealth. Instead of deleting health, do this:
public class PlayerStats : MonoBehaviour
{
[SerializeField] private int maxHealth; // The new variable
[SerializeField, HideInInspector] private int health; // The legacy variable
private void OnValidate()
{
// If we have legacy data but no new data, migrate it
if (health != 0 && maxHealth == 0)
{
maxHealth = health;
health = 0; // Clear it so we don't migrate twice
}
}
}
By keeping the legacy field, Unity keeps the data alive in the background. The OnValidate method acts as a bridge, ensuring that the next time you open a scene or select a Prefab, the old data is automatically assigned to your new structure. Once you are confident that every asset in your project has been updated (verified via search or playtesting), you can safely remove the legacy field in a future release.
This process ensures that your team’s hard-earned tweaks in the Inspector remain intact, even as your game’s architecture grows more complex. Always treat your serialized data as a living asset that requires a transition path whenever the underlying code changes.
Key Takeaway: Never delete serialized variables directly; use hidden legacy fields and migration logic to move data into your new structures, ensuring your assets remain compatible throughout development.