0
0
Unityframework~5 mins

ScriptableObjects for game data in Unity

Choose your learning style9 modes available
Introduction

ScriptableObjects help you store game data separately from code. This makes your game easier to manage and change without rewriting code.

You want to create reusable game settings like player stats or weapon info.
You need to share data between different parts of your game without copying it.
You want to tweak game values in the Unity Editor without changing scripts.
You want to keep your game data organized and easy to update.
You want to reduce memory use by sharing data instead of duplicating it.
Syntax
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.

Examples
This example shows a ScriptableObject for weapon data with name, damage, and range.
Unity
using UnityEngine;

[CreateAssetMenu(fileName = "NewWeaponData", menuName = "Game Data/Weapon")]
public class WeaponData : ScriptableObject
{
    public string weaponName;
    public int damage;
    public float range;
}
This example stores level information like name and difficulty.
Unity
using UnityEngine;

[CreateAssetMenu(fileName = "NewLevelData", menuName = "Game Data/Level")]
public class LevelData : ScriptableObject
{
    public string levelName;
    public int difficulty;
}
Sample Program

This program defines a PlayerStats ScriptableObject with default values. The Player MonoBehaviour uses this data and prints it when the game starts.

Unity
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}");
    }
}
OutputSuccess
Important Notes

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.

Summary

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.