将 ScriptableObject 列表保存到 json

Saving a list of ScriptableObject into json

我的物品脚本

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

[CreateAssetMenu(fileName ="Newitems",menuName ="Inventory/Items")]
[Serializable]
public class Item : ScriptableObject
{

  new public string name = "New items";  
  //public Sprite Icon = null;      dealt with this later        
  public bool isDefaulet = false;
  ...} 

这是我的清单脚本:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System;
[Serializable]
public class Inventory : MonoBehaviour
{
   [SerializeField]
public List<Item> items = new List<Item>();
 void Save()
    {
        string json = JsonUtility.ToJson(items);
        Debug.Log(json);
        File.WriteAllText(Application.dataPath + "/saveFile.json", json);
    }
    public void Load()
    {
        string json = File.ReadAllText(Application.dataPath + "/saveFile.json");
        List<Item> List = JsonUtility.FromJson<List<Item>>(json);
        Debug.Log(List);
    }
...
 }

好的,我稍后会尝试使用精灵,但是在保存时,控制台return {},我现在不知道,请帮助。

在 json 中保存脚本的第一件事是在每个要在 json 中序列化的脚本上添加 class 属性 Serializable。

但在这里我认为很难序列化图标字段。在 json 中你真的只能保存数字或字符串并且有一个引用。

序列化 Sprite(或任何引用)的一种方法是序列化对象的名称或 ID。如果你看看 unity 如何序列化一个场景,它就是这样做的。 然后,当您阅读 json 时,您会用您的资产替换该 ID。

一些json库可以帮忙,NewtonSoft Json.Net可以帮忙,特别是我描述的特殊序列化供参考。

先在没有 Sprite 的情况下尝试,然后再添加复杂性 ;)

编辑

更准确地说,我认为更好的方法是不序列化 ScriptableObject,而是 class 由脚本保持。

class MyScriptable : ScriptableObject
{
    private MySerializableClass data;
}

[Serializable]
class MySerializableClass 
{
    private string name;
    private float data1;
    private float data2;
}

然后序列化 MySerializableClass,并使用名称或一些 id 字段 link 每个具有良好 MySerializableClass 的可编写脚本的实例:)