Is it possible to serialize sprites in unity?

前端 未结 1 1746
孤城傲影
孤城傲影 2021-01-13 17:20

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 audiocl

相关标签:
1条回答
  • 2021-01-13 17:56

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

    }

    0 讨论(0)
提交回复
热议问题