CodeBlanks Logo Icon CodeBlanks

ItemData ScriptableObject

Learn to define item data with a ScriptableObject.

What is ScriptableObject?

ScriptableObject is a class type that stores game data as an asset. It does not need to be added to the scene; it sits as a project file and is used when needed. It is ideal for repeating data such as item information.

using UnityEngine;

[CreateAssetMenu(fileName = "YeniOge", menuName = "Envanter/Oge")]
public class ItemData : ScriptableObject
{
    public string ogeAdi;
}

This class can now be created from the Project window.

ItemData and the asset

ItemData holds all the information about an item: its name, type and stack limit. Because this class is a ScriptableObject, a separate asset file is created for each item. This way the same data can be reused in many places.

oge.ogeAdi = "Kilic";
oge.yiginLimiti = 1;

Asset files are easily edited through the Inspector.

Practice Create item data

In a class named OgeVerisi, define a string ogeAdi field with the value "Kilic" and an int yiginLimiti field with the value 5. In the Start method, print the pieces "Oge: ", ogeAdi, " Limit: " and yiginLimiti joined together with Debug.Log.

Starter code

Player.cs
using UnityEngine;

public class OgeVerisi : MonoBehaviour
{
    // string ogeAdi alanini "Kilic", int yiginLimiti alanini 5 degeriyle tanimla

    void Start()
    {
        // "Oge: " + ogeAdi + " Limit: " + yiginLimiti biciminde yazdir
    }
}

Sample solution

Player.cs
using UnityEngine;

public class OgeVerisi : MonoBehaviour
{
    string ogeAdi = "Kilic";
    int yiginLimiti = 5;

    void Start()
    {
        Debug.Log("Oge: " + ogeAdi + " Limit: " + yiginLimiti);
    }
}

Expected output

Oge: Kilic Limit: 5

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What sets ScriptableObject apart?

  • It must be added to the scene
  • It speeds up lighting calculations
  • It only builds the interface
  • It stores data as an asset, without being added to the scene Correct answer

Explanation: A ScriptableObject is not a scene object but a project file, which is why it carries reusable data.

2 Derive the ItemData class

Question
using UnityEngine;

public class ItemData : ____
{
    public string ogeAdi;
}
Answer
using UnityEngine;

public class ItemData : ScriptableObject
{
    public string ogeAdi;
}

Explanation: ItemData is a data class so it derives from ScriptableObject, not from MonoBehaviour.

3 ScriptableObject terms

Term Meaning
ScriptableObject A class type that stores data
Asset A project file
ItemData The class that holds item info
CreateAssetMenu The menu that creates a new asset

All lessons in Advanced