Open HunterAhlquist opened 2 years ago
Hello @HunterAhlquist, thanks for reporting this!
Sad to say that there's some technical issues with this, which is why this package don't support Sprites at the moment.
Some of the fields are no biggie, such as:
Sprite.bounds
Sprite.rect
Sprite.border
Sprite.pixelsPerUnit
Sprite.spriteAtlasTextureScale
Sprite.pivot
Sprite.packed
However, some other fields are less straight forward. Such as:
Sprite.texture
Sprite.associatedAlphaSplitTexture
Sprite.m_CachedPtr
(inherited from UnityEngine.Object
)Sprite.m_InstanceID
(inherited from UnityEngine.Object
)Especially the latter two makes it impossible to simply just create new objects on the fly when deserializing. Instead, I have to call Sprite.Create
or something similar, which allocates a lot, does not reference your internal assets, and will duplicate the sprites if they are referenced multiple times in the project.
Depending on your use case, I suggest to either:
Use AssetReference from the Addressables package, which is supported since v1.4.0 of Newtonsoft.Json-for-Unity.Converters.
This would allow you to make sure to reuse the same exact asset without excessive allocations and texture duplications. The JSON would then only include the GUID of the asset.
Use a custom type for Sprite, that includes all the fields you want to transfer via JSON. Ex:
public class SpriteData
{
public Bounds bounds;
public Rect rect;
public Vector4 border;
public float pixelsPerUnit;
public float spriteAtlasTextureScale;
public Vector2 pivot;
public bool packed;
// add other fields you care about
}
Use this if your use case orients around the metadata for a sprite. What you'd do is to new SpriteData()
and then assign all fields based on a Unity Sprite
asset. If you want to apply the state back to a Unity Sprite
asset then you do the reverse and assign the fields from the SpriteData
on to the Unity Sprite
assets.
Then to get your ScriptableObject to not error because of the Sprite reference, you can add the [JsonIgnore]
attribute to that field.
Write a custom JSON converter yourself. If you don't care about the asset reference loss, sprite duplications overhead, or other things like that, then you can create a SpriteConverter that suits your use case precisely.
Expected behavior
Serialized ScriptableObject with Sprite reference gets initialized through its converter.
Actual behavior
Throws a NullReferenceException:
Call Stack
NullReferenceException UnityEngine.Sprite.get_bounds () (at
Steps to reproduce
jillejr.newtonsoft.json-for-unity
via UPMjillejr.newtonsoft.json-for-unity.converters
via UPMDetails
Host machine OS running Unity Editor 👉 Windows
Unity build target 👉 Windows, Mac, Linux
Newtonsoft.Json-for-Unity package version 👉 10.0.302
Newtonsoft.Json-for-Unity.Converters package version 👉 1.4.0
I was using Unity version 👉 2020.3.26f1
Checklist