0
0
Unityframework~15 mins

ScriptableObjects for game data in Unity - Deep Dive

Choose your learning style9 modes available
Overview - ScriptableObjects for game data
What is it?
ScriptableObjects are special data containers in Unity that let you store game data separately from game objects. They hold information like stats, settings, or configurations that can be reused across your game. Unlike normal objects, they exist as assets in your project, making data easy to manage and share. This helps keep your game organized and efficient.
Why it matters
Without ScriptableObjects, game data often lives inside game objects or scripts, which can cause duplication and make changes hard to track. This leads to messy projects and bugs when data is inconsistent. ScriptableObjects solve this by centralizing data, making it easy to update and reuse without changing code or prefabs. This saves time and reduces errors, especially in bigger games.
Where it fits
Before learning ScriptableObjects, you should understand Unity basics like GameObjects, Components, and how to create scripts. After mastering ScriptableObjects, you can explore advanced data-driven design patterns, custom editors, and asset management to build scalable games.
Mental Model
Core Idea
ScriptableObjects are like reusable data files that live outside your game scenes, letting you share and manage game data easily and cleanly.
Think of it like...
Imagine a recipe book that holds all your cooking recipes separately from your kitchen tools. Instead of writing recipes on each tool, you keep them in one book to use anytime. ScriptableObjects are like that recipe book for your game data.
┌─────────────────────────────┐
│        ScriptableObject      │
│  (Data asset stored on disk) │
└─────────────┬───────────────┘
              │
   ┌──────────┴───────────┐
   │                      │
┌───────┐            ┌────────┐
│Enemy 1│            │Enemy 2 │
│uses   │            │uses    │
│Script-│            │Script- │
│ableObj│            │ableObj │
└───────┘            └────────┘
Build-Up - 6 Steps
1
FoundationWhat are ScriptableObjects
🤔
Concept: Introduce ScriptableObjects as Unity assets that store data separately from scenes and objects.
In Unity, ScriptableObjects are special objects that hold data and live as assets in your project folder. You create them by making a class that inherits from ScriptableObject and then create instances saved as files. These files can hold things like character stats, item info, or game settings.
Result
You get a reusable data file that can be shared across multiple game objects and scenes.
Understanding that ScriptableObjects are assets, not scene objects, helps you see how data can be centralized and reused without duplication.
2
FoundationCreating and Using ScriptableObjects
🤔
Concept: Learn how to define a ScriptableObject class and create instances in Unity.
To create a ScriptableObject, write a class inheriting from ScriptableObject. Add the CreateAssetMenu attribute to make it easy to create instances from Unity's menu. Then, create an asset file in your project. You can reference this asset in your scripts to access the data it holds.
Result
You can create and edit data assets in the Unity editor that your game code can read.
Knowing how to create and reference ScriptableObjects unlocks their power to separate data from behavior.
3
IntermediateSharing Data Across Multiple Objects
🤔Before reading on: Do you think each game object needs its own copy of data, or can they share one ScriptableObject instance? Commit to your answer.
Concept: ScriptableObjects allow multiple game objects to share the same data instance, avoiding duplication.
Instead of copying data into each game object, you assign the same ScriptableObject asset to many objects. For example, many enemies can share one ScriptableObject that holds their stats. Changing the asset updates all enemies at once.
Result
All objects referencing the ScriptableObject see the same data, making updates easy and consistent.
Understanding shared data prevents bugs from inconsistent copies and simplifies balancing and tweaking.
4
IntermediateModifying ScriptableObjects at Runtime
🤔Before reading on: Do you think changes to ScriptableObjects during gameplay affect the saved asset or just the current session? Commit to your answer.
Concept: Changes to ScriptableObjects at runtime affect only the current game session, not the saved asset file.
When you modify a ScriptableObject in play mode, the changes happen in memory and reset when you stop playing. The asset file on disk stays unchanged unless you explicitly save changes via editor scripting.
Result
Runtime changes do not persist after exiting play mode, keeping your original data safe.
Knowing this prevents confusion about why data resets and guides you to use ScriptableObjects mainly for static or shared data.
5
AdvancedUsing ScriptableObjects for Event Systems
🤔Before reading on: Can ScriptableObjects be used to decouple game systems by acting as event channels? Commit to your answer.
Concept: ScriptableObjects can act as event channels to send messages between game systems without direct references.
Create ScriptableObjects that hold event data and listeners. Game objects can subscribe to these events and respond when the ScriptableObject triggers them. This decouples systems and improves modularity.
Result
You get a flexible event system that reduces tight coupling and improves code organization.
Understanding ScriptableObjects as communication channels expands their use beyond just data storage.
6
ExpertAvoiding Common Pitfalls with ScriptableObjects
🤔Before reading on: Do you think modifying ScriptableObjects directly in play mode is safe for persistent game data? Commit to your answer.
Concept: Modifying ScriptableObjects directly in play mode can cause unintended data loss or bugs if not handled carefully.
Because runtime changes to ScriptableObjects do not persist, relying on them for saving player progress or dynamic data is risky. Instead, use them for static data and copy their values into runtime objects for changes. Also, be cautious with references to avoid accidental shared state bugs.
Result
You avoid confusing bugs and data loss by using ScriptableObjects correctly in production.
Knowing the limits of ScriptableObjects in runtime data management prevents costly mistakes in game design.
Under the Hood
ScriptableObjects are serialized assets stored as files in the Unity project. When the game runs, Unity loads these assets into memory as shared instances. They do not exist in the scene hierarchy but can be referenced by scene objects. At runtime, changes to these instances affect only the in-memory copy, not the saved asset file. Unity's serialization system handles saving and loading their data automatically.
Why designed this way?
Unity designed ScriptableObjects to separate data from behavior and scene objects, improving project organization and performance. Before ScriptableObjects, developers often duplicated data in prefabs or scripts, causing maintenance headaches. ScriptableObjects provide a lightweight, asset-based solution that supports reuse and easy editing without bloating scenes.
┌───────────────┐       ┌───────────────┐
│ ScriptableObj │──────▶│ Serialized    │
│ Class in Code │       │ Asset File    │
└──────┬────────┘       └──────┬────────┘
       │                       │
       │ Runtime Load          │
       ▼                       ▼
┌───────────────┐       ┌───────────────┐
│ In-Memory     │       │ Scene Objects │
│ Instance      │◀──────│ Reference    │
└───────────────┘       └───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do you think modifying a ScriptableObject in play mode changes the saved asset permanently? Commit to yes or no.
Common Belief:Modifying ScriptableObjects during gameplay saves changes to the asset file permanently.
Tap to reveal reality
Reality:Changes made to ScriptableObjects at runtime only affect the current session and reset when play mode ends.
Why it matters:Believing otherwise can cause confusion when data resets unexpectedly, leading to wasted debugging time.
Quick: Do you think each game object needs its own unique ScriptableObject instance to avoid data conflicts? Commit to yes or no.
Common Belief:Each game object should have its own ScriptableObject instance to prevent shared data issues.
Tap to reveal reality
Reality:Multiple game objects can and often should share the same ScriptableObject instance to keep data consistent and reduce duplication.
Why it matters:Misunderstanding this leads to unnecessary asset duplication and harder maintenance.
Quick: Do you think ScriptableObjects can replace all data storage needs, including player progress? Commit to yes or no.
Common Belief:ScriptableObjects are suitable for saving all types of game data, including dynamic player progress.
Tap to reveal reality
Reality:ScriptableObjects are best for static or shared data; dynamic data like player progress should use other systems like PlayerPrefs or custom save files.
Why it matters:Using ScriptableObjects for dynamic data can cause data loss and bugs.
Quick: Do you think ScriptableObjects are just fancy MonoBehaviours? Commit to yes or no.
Common Belief:ScriptableObjects are similar to MonoBehaviours and can be used interchangeably.
Tap to reveal reality
Reality:ScriptableObjects do not live in scenes and have no lifecycle like MonoBehaviours; they are purely data containers.
Why it matters:Confusing these leads to misuse and misunderstanding of Unity's architecture.
Expert Zone
1
ScriptableObjects can be used to create modular, data-driven architectures that separate configuration from code logic, improving scalability.
2
Custom editor scripts can extend ScriptableObjects to provide rich editing experiences, validation, and automation inside the Unity Editor.
3
ScriptableObjects support inheritance and polymorphism, allowing complex data hierarchies and flexible game design patterns.
When NOT to use
Avoid using ScriptableObjects for data that changes frequently at runtime or needs to be saved persistently per player. Instead, use runtime data structures, databases, or Unity's PlayerPrefs and serialization systems.
Production Patterns
In production, ScriptableObjects often store game balance data, item definitions, audio settings, and event channels. Teams use them to enable designers to tweak values without code changes and to decouple systems for easier testing and maintenance.
Connections
Data-Driven Design
ScriptableObjects implement data-driven design by separating data from code.
Understanding ScriptableObjects helps grasp how data-driven design enables flexible and maintainable game development.
Observer Pattern
ScriptableObjects can act as event channels implementing the observer pattern.
Knowing this connection reveals how ScriptableObjects facilitate loose coupling and communication between game systems.
Database Normalization
ScriptableObjects centralize data like normalized database tables to avoid duplication.
Seeing ScriptableObjects as a form of data normalization helps understand their role in reducing redundancy and improving consistency.
Common Pitfalls
#1Modifying ScriptableObject data directly in play mode expecting changes to persist.
Wrong approach:myScriptableObject.health = 100; // changed during play mode, expecting permanent save
Correct approach:Copy data from ScriptableObject to runtime object, modify runtime data, and save externally if needed.
Root cause:Misunderstanding that runtime changes to ScriptableObjects do not affect the saved asset file.
#2Creating multiple ScriptableObject instances for the same data leading to duplication.
Wrong approach:Creating separate ScriptableObject assets for each enemy with identical stats.
Correct approach:Create one ScriptableObject asset and assign it to all enemies that share the same stats.
Root cause:Not realizing ScriptableObjects are designed for shared reusable data.
#3Using ScriptableObjects to store player progress or dynamic runtime data.
Wrong approach:Saving player score or inventory directly in a ScriptableObject asset.
Correct approach:Use PlayerPrefs, JSON files, or databases for dynamic and persistent player data.
Root cause:Confusing static configuration data with dynamic runtime data storage.
Key Takeaways
ScriptableObjects are Unity assets designed to store reusable game data separately from scenes and objects.
They enable sharing data across multiple game objects, reducing duplication and easing maintenance.
Runtime changes to ScriptableObjects do not persist after play mode, so they are best for static or shared data.
ScriptableObjects can also be used as event channels to decouple game systems and improve modularity.
Misusing ScriptableObjects for dynamic or persistent data leads to bugs; understanding their purpose is key to effective game design.