BinaryFormatter gives error that Sprite is not serializable. How to do it?
Or, is there a way to get the file name from the sprite and then serialize as string?
Thanks & Regards
Raj
BinaryFormatter gives error that Sprite is not serializable. How to do it?
Or, is there a way to get the file name from the sprite and then serialize as string?
Thanks & Regards
Raj
I got it working… Though it may not be the best method…
I got the path of the sprite image file using AssetDatabase.GetAssetPath(), (And retrieved the file name only using Path.GetFileNameWithoutExtension() ), and serialized it as string.
Also, I had to put my sprite assets under the resources folder. Appears to be working fine.
Putting sprites in Resources is not recommended because if you do that they can’t be auto-atlased (if you have Pro).
–Eric
Thanks for the response.
Thanks & Regards
I’d like to bump this to see if anybody has found a solution to actually do this without putting it all in the resources folder, thus restricting yourself to the sprites in those folders and foregoing the huge benefits of not having to know what atlas a sprite is in in order for it to batch.
Essentially, I just want to do what Unity already does: Find a sprite by a serialized reference at runtime. However, not from an instantiated MonoBehaviour. So, like this:
[System.Serializable]
public class ItemData
{
//this doesn't serialize, sadly... and its GUID cannot be used at runtime (D'oh!)
UnityEngine.Sprite sprite;
}
I can imagine why we’re not allowed to do this (it’d be next to impossible to ensure an asset is compiled to a runtime build if we’re all haphazardly storing references outside of scene files), but it’d be really nice to find away to do it anyway.
Here’s how a Scene file stored the references, for instance: {fileID: 21300000, guid: 0514b8ab7013b4d90ad589edb6f17993, type: 3}
EDIT: Created a generic workaround for this: Manually update serialized asset references for build - Unity Engine - Unity Discussions (might be even more generic by turning DataContainer into a template class, but don’t know if that would still work)
7 Years Later…:
You can avoid AssetDatabase.GetAssetPath() if your sprites (for this instance) are all in the same (Resources) folder. Then you can cheat a bit with something like this:
[Serializable]
public struct ItemData{
[SerializeField] private string spritePath;
public Sprite portrait => Resources.Load<Sprite>(spritePath);
public ItemData(Sprite sprite) {
spritePath = sprite.name;
}
}
This is fully serializable and is an opaque facade on just using the Sprite directly: in other words, you should be able to sub this in without any other changes to your code.