Unity:将 Sprite 保存/加载为 Json

Maj*_*ajs 5 c# json unity-game-engine

我正在遵循一个教程,其中我需要保存属于某个对象的精灵。我正在创建一个项目数据库,当然希望该项目附带正确的图像。这就是我构建项目数据库的方式:

项目对象

[System.Serializable]
public class ItemObject{

    public int id;
    public string title;
    public int value;
    public string toolTip;
    public bool stackable;
    public string category;
    public string slug;
    public Sprite sprite;


    public ItemObject(int id, string title, int value, string toolTip, bool stackable, string category, string slug)
    {
        this.id = id;
        this.title = title;
        this.value = value;
        this.toolTip = toolTip;
        this.stackable = stackable;
        this.category = category;
        this.slug = slug;
        sprite = Resources.Load<Sprite>("items/" + slug);
    }
Run Code Online (Sandbox Code Playgroud)

项目数据

[System.Serializable]
public class ItemData {

    public List<ItemObject> itemList;

}
Run Code Online (Sandbox Code Playgroud)

然后我保存/加载 ItemData.itemList。效果很好。正如你所看到的,我使用“slug”来加载我的物品的精灵,slug 基本上是一个代码友好的名称(例如:golden_hat),然后我的精灵有相同的名称。

这也很好用,但是 Unity 会保存 Sprite InstanceID,它总是在启动时发生变化,因此如果我退出 Unity 并加载数据,它将获得错误的图像。

我的杰森:

{
    "itemList": [
        {
            "id": 0,
            "title": "Golden Sword",
            "value": 111,
            "toolTip": "This is a golden sword",
            "stackable": false,
            "category": "weapon",
            "slug": "golden_sword",
            "sprite": {
                "instanceID": 13238
            }
        },
        {
            "id": 1,
            "title": "Steel Gloves",
            "value": 222,
            "toolTip": "This is steel gloves",
            "stackable": true,
            "category": "weapon",
            "slug": "steel_gloves",
            "sprite": {
                "instanceID": 13342
            }
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

所以我猜这样做是行不通的,还有其他方法可以在 Json 中保存 Sprite 吗?或者我每次使用我的“slug”都必须在运行时加载正确的精灵?

Eve*_*rts 1

更合适的方法是将纹理保存为 byte [],然后你的 json 包含 byte [] 的名称或 url。

    {
        "id": 1,
        "title": "Steel Gloves",
        "value": 222,
        "toolTip": "This is steel gloves",
        "stackable": true,
        "category": "weapon",
        "slug": "steel_gloves",
        "sprite": "steelgloves"
    }
Run Code Online (Sandbox Code Playgroud)

然后,当您获取 json 时,将其转换为 C# 并查找字节数组。一旦获得了字节数组,就可以重建精灵:

byte [] bytes = File.ReadAllBytes(path);
Texture2d tex = new Texture2D(4,4);
tex.LoadImage(bytes);
Sprite sp = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f,0.5f));
Run Code Online (Sandbox Code Playgroud)