可以统一序列化精灵吗? [英] Is it possible to serialize sprites in unity?
本文介绍了可以统一序列化精灵吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在开发一些游戏,这些游戏应该通过文件相互通信.我试图在游戏之间发送的一件事是一个精灵和一个音频剪辑,但似乎不起作用.我正在使用以下课程.
I'm working on some games that are suppose to communicate with one another trough a file. One of the things i am trying to send between the games is a sprite and an audioclip but it doesn't seem to work. I'm using the following class.
[Serializable]
class Data
{
public Sprite spriteToSend;
public AudioClip clipToSend;
}
我也在使用BinaryFormatter来保存我的数据
I'm also using BinaryFormatter to save my data like so
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath +"/Data.dat");
Data data = new ;
bf.Serialize(file, data);
file.Close();
并像这样加载它
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "\\Data.dat", FileMode.Open);
Data data = (Data)bf.Deserialize(file);
file.Close();
但是当我运行它时,出现一个错误,指出精灵和音频片段无法序列化.
but when i run it i get an error that says sprites and audioclips cant be Serialized.
我做错了什么或如何解决此问题?
Am i doing something wrong or how can i solve this problem?
推荐答案
如果要序列化,则需要使用纹理
if you want to serialize, then you need to do it with texture
public class TEST : MonoBehaviour {
[SerializeField]
Sprite m_InSprite;
SerializeTexture exportObj = new SerializeTexture();
SerializeTexture importObj = new SerializeTexture();
[ContextMenu("serialize")]
public void SerializeTest()
{
Texture2D tex = m_InSprite.texture;
exportObj.x = tex.width;
exportObj.y = tex.height;
exportObj.bytes = ImageConversion.EncodeToPNG(tex);
string text = JsonConvert.SerializeObject(exportObj);
File.WriteAllText(@"d:\test.json", text);
}
[ContextMenu("deserialize")]
public void DeSerializeTest()
{
string text = File.ReadAllText(@"d:\test.json");
importObj = JsonConvert.DeserializeObject<SerializeTexture>(text);
Texture2D tex = new Texture2D(importObj.x, importObj.y);
ImageConversion.LoadImage(tex,importObj.bytes);
Sprite mySprite = Sprite.Create(tex, new Rect(0.0f, 0.0f, tex.width, tex.height), Vector2.one);
GetComponent<Image>().sprite = mySprite;
}
[Serializable]
public class SerializeTexture
{
[SerializeField]
public int x;
[SerializeField]
public int y;
[SerializeField]
public byte[] bytes;
}
}
这篇关于可以统一序列化精灵吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文