Loading lessons...
ScriptableObjects
ScriptableObjects
A ScriptableObject is a data container that you can use to save large amounts of shared data, independent of GameObject instances.
ScriptableObjects vs MonoBehaviours
- MonoBehaviour: Attached to GameObjects. Every instance in the scene copies all variables, consuming duplicate memory.
- ScriptableObject: Stored as an asset file in your project. Multiple GameObjects can reference a single ScriptableObject asset, sharing its data.
Declaring a ScriptableObject
Inherit from ScriptableObject instead of MonoBehaviour:
using UnityEngine;
[CreateAssetMenu(fileName = "NewItemData", menuName = "Inventory/Item Data")]
public class ItemData : ScriptableObject
{
public string itemName;
public Sprite icon;
public int goldValue;
}
The [CreateAssetMenu] attribute allows you to create instances of this data file directly in the Project Window by right-clicking and selecting Create -> Inventory -> Item Data.
Practical Uses
- Weapon/Item Stats: Configuring bullet damage, speed, and fire rates.
- Game Configurations: Storing level data or difficulty settings.
- Pluggable AI States: Storing modular AI behaviors.
TL;DR
- ScriptableObjects are assets that store configuration or shared data.
- They do not attach to GameObjects, which saves scene memory.
- Use the
CreateAssetMenuattribute to create data assets in the Project window. - Multiple GameObjects can reference a single ScriptableObject asset.