Saving Items (Scriptable Objects)

Hey, I’m currently programming a game where you can craft more and more items.
The problem is that the items are not saved when I close the game.
I’ve already looked at tutorials on how to save scribtable objects, but that does not really work.

I have already written a GameSave script and now I just need to know how to program it to automatically save the items…

GameSave script:

using UnityEngine;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
public static class GameSave
{
    public static void saveItem (Item item)
    {
        BinaryFormatter formatter = new BinaryFormatter();
        string path = Application.persistentDataPath + "/item.fun";
        FileStream stream = new FileStream(path, FileMode.Create);

        ItemData data = new ItemData(item);

        formatter.Serialize(stream, data);
        stream.Close();


    }

    public static ItemData loadPlayer()
    {
        string path = Application.persistentDataPath + "/item.fun";
        if (File.Exists(path))
        {
            BinaryFormatter formatter = new BinaryFormatter();
            FileStream stream = new FileStream(path, FileMode.Open);

            ItemData data = formatter.Deserialize(stream) as ItemData;
            stream.Close();

            return data;
        }
        else
        {
            return null;
        }
    }


}

Item scriptable object:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[CreateAssetMenu(fileName = "New Item", menuName = "Item")]
public class Item : ScriptableObject {

    public Sprite icon;
    [TextArea]
    public string discoveryText;
    public string discoveryTitle;

    public Color customColor = Color.black;

    public string customSound;

    [HideInInspector]
    public GameObject itemObject;


  
}

Item Display script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class ItemDisplay : MonoBehaviour
{

    public Item item;
    public Image icon;
    public TextMeshProUGUI nameText;

    public void Setup(Item _item)
    {
        item = _item;
        icon.sprite = item.icon;
        nameText.text = item.name;
    }




 



}

It’s a bit tricky to save sprites; I forget how exactly but google should help there. Generally you wouldn’t bother saving the sprite of an item; a chunk of wood will usually look the same.

I also recommend using JSON instead of binary serializers, which will produce readable text instead of binary junk. This will make it a LOT easier for you to debug and figure out what stuff is failing to serialize.

1 Like

This asset is a life saver:

2 Likes