0
0
Unityframework~3 mins

Why Variables and serialization in Unity? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your game could remember everything automatically without you writing endless save code?

The Scenario

Imagine you are making a game in Unity and want to save the player's score and settings so they don't lose progress when they close the game.

You try to write all the data manually every time the player changes something, but it quickly becomes confusing and messy.

The Problem

Manually saving and loading each piece of data is slow and easy to forget.

You might save the wrong value or miss some important information, causing bugs and lost progress.

It also makes your code long and hard to read.

The Solution

Using variables and serialization in Unity lets you store data neatly and automatically save or load it as needed.

Serialization turns your variables into a format that Unity can save to a file or memory, so you don't have to write all the saving code yourself.

Before vs After
Before
PlayerPrefs.SetInt("score", score);
PlayerPrefs.SetString("playerName", name);
After
[System.Serializable]
public class PlayerData {
  public int score;
  public string playerName;
}

// Use JsonUtility.ToJson to serialize and save to file or PlayerPrefs
What It Enables

You can easily save and load complex game data, making your game remember player progress and settings without extra hassle.

Real Life Example

Think of a game where you collect coins and unlock levels. Serialization saves your coin count and unlocked levels so you can continue exactly where you left off.

Key Takeaways

Manual saving is slow and error-prone.

Serialization automates saving variables in Unity.

This keeps your game data safe and your code clean.