ScriptableObjects help you store game data separately from code. This makes your game easier to manage and change without rewriting code.
ScriptableObjects for game data in Unity
using UnityEngine; [CreateAssetMenu(fileName = "NewGameData", menuName = "Game Data/Player Stats")] public class PlayerStats : ScriptableObject { public int health; public int mana; public float speed; }
The [CreateAssetMenu] attribute lets you create this data from Unity's menu.
ScriptableObjects are classes that inherit from ScriptableObject, not MonoBehaviour.
using UnityEngine; [CreateAssetMenu(fileName = "NewWeaponData", menuName = "Game Data/Weapon")] public class WeaponData : ScriptableObject { public string weaponName; public int damage; public float range; }
using UnityEngine; [CreateAssetMenu(fileName = "NewLevelData", menuName = "Game Data/Level")] public class LevelData : ScriptableObject { public string levelName; public int difficulty; }
This program defines a PlayerStats ScriptableObject with default values. The Player MonoBehaviour uses this data and prints it when the game starts.
using UnityEngine; [CreateAssetMenu(fileName = "PlayerStatsData", menuName = "Game Data/Player Stats")] public class PlayerStats : ScriptableObject { public int health = 100; public int mana = 50; public float speed = 5.5f; } public class Player : MonoBehaviour { public PlayerStats stats; void Start() { Debug.Log($"Player Health: {stats.health}"); Debug.Log($"Player Mana: {stats.mana}"); Debug.Log($"Player Speed: {stats.speed}"); } }
You create ScriptableObject assets in Unity by right-clicking in the Project window and selecting the menu you set in [CreateAssetMenu].
ScriptableObjects keep data even when you stop playing the game in the Editor.
They are great for data that many objects share, like enemy types or item stats.
ScriptableObjects store game data separately from code for easy reuse and editing.
Use [CreateAssetMenu] to make creating data assets simple in Unity.
They help keep your game organized and reduce memory use by sharing data.