Is it possible to serialize sprites in unity?

Viewed 5936

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;
}

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();

and to load it like so

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?

1 Answers

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;
}

}

Related