Search Unity

Save Scriptable Object List of Gameobjects

Discussion in 'Scripting' started by sebhah, Oct 27, 2020.

  1. sebhah

    sebhah

    Joined:
    Jan 6, 2019
    Posts:
    26
    Hello, I've an problem with my save system.

    When you run the game in the unity editor and do some changes in an scriptable object it saves it by it self, but if you build the game and you change something to an scriptable object is won't save.

    But I've an Scriptable Object (class inventorycar) and I want it that if you add or remove an item that is save the changes. But I got an problem. Possible somebody can help me with this problem.
    Thankyou in advance !

    Code (CSharp):
    1. using System.Collections.Generic;
    2. using System.IO;
    3. using System.Linq;
    4. using System.Runtime.Serialization.Formatters.Binary;
    5. using UnityEditor;
    6. using UnityEngine;
    7.  
    8. Class 1:
    9. [System.Serializable]
    10. [CreateAssetMenu(fileName = "Data", menuName = "Inventory/L istCar", order = 1)]
    11. public class InventoryCar : ScriptableObject {
    12.     public List<ItemCar> InventoryItem = new List<ItemCar>();
    13.     public bool b_mobile = false;
    14.     public float mobileMaxSpeedOffset = 0;
    15.     public float mobileWheelStearingOffsetReactivity = 0;
    16.     public bool b_Countdown = true;
    17.     public bool b_LapCounter = true;
    18.  
    19.     public int SavedListCount;
    20.  
    21.  
    22.     public void SaveList()
    23.     {
    24.         for (int i = 0; i < InventoryItem.Count; i++)
    25.         {
    26.             PlayerPrefs.SetString("TotalCars" + i, InventoryItem[i].Cars.());
    27.         }
    28.         PlayerPrefs.SetInt("Count", InventoryItem.Count);
    29.     }
    30.  
    31.     public void LoadList()
    32.     {
    33.         InventoryItem.Clear();
    34.         SavedListCount = PlayerPrefs.GetInt("Count");
    35.  
    36.         for (int i = 0; i < SavedListCount; i++)
    37.         {
    38.             ItemCar cars = PlayerPrefs.GetString("TotalCars" + i.ToString());
    39.             InventoryItem.Add(cars);
    40.         }
    41.     }
    Script 2:

    Code (CSharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5.  
    6. [System.Serializable]
    7. public class ItemCar
    8. {
    9.     [SerializeField]
    10.     public List<GameObject> Cars = new List<GameObject>();
    11.  
    12.    
    13. }
    14.  
     
  2. MadeFromPolygons

    MadeFromPolygons

    Joined:
    Oct 5, 2013
    Posts:
    3,980
    At runtime you will need to first serialize the SO to disk, and then read from there and convert back to load.

    SO is not mutable at runtime. So you can adapt your code so that after saving to the SO, it then uses JSON to serialize, or binaryformatter or any other way of serializing to disk quickly.

    Good luck :)