c# – Unity:将精灵保存/加载为Json
发布时间:2020-12-15 22:44:58 所属栏目:百科 来源:网络整理
导读:我正在按照教程我需要保存属于对象的精灵. 我正在创建一个项目数据库,当然希望项目附带正确的图像.这就是我构建Item数据库的方法: ItemObject [System.Serializable]public class ItemObject{ public int id; public string title; public int value; publi
我正在按照教程我需要保存属于对象的精灵.
我正在创建一个项目数据库,当然希望项目附带正确的图像.这就是我构建Item数据库的方法: ItemObject [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); } 的ItemData [System.Serializable] public class ItemData { public List<ItemObject> itemList; } 然后我保存/加载ItemData.itemList.这很好用.如你所见,我使用“slug”来加载我的Item的精灵,slug基本上是一个代码友好的名字(例如:golden_hat),然后我的Sprite名字相同. 这也很好用,但Unity保存了Sprite InstanceID,它始终在启动时更改,所以如果我退出Unity并加载我的数据,它将得到错误的Image. 我的Json: { "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,"slug": "steel_gloves","sprite": { "instanceID": 13342 } } ] } 所以我猜它不会这样做,有没有其他方法来保存Json中的Sprite?或者每次使用我的“slug”时我是否必须在运行时加载正确的Sprite? 解决方法
更合适的方法是将纹理保存为byte [],然后你的json包含byte []的名称或url.
{ "id": 1,"sprite": "steelgloves" } 然后当你抓住json时,转换为C#并查找字节数组.一旦你有字节数组,你可以重建精灵: byte [] bytes = File.ReadAllBytes(path); Texture2d tex = new Texture2D(4,4); tex.LoadImage(bytes); Sprite sp = Sprite.Create(tex,new Rect(0,tex.width,tex.height),new Vector2(0.5f,0.5f)); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |