我正在按照教程我需要保存属于对象的精灵.
我正在创建一个项目数据库,当然希望项目附带正确的图像.这就是我构建Item数据库的方法:
我正在创建一个项目数据库,当然希望项目附带正确的图像.这就是我构建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));
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。