Created
April 7, 2021 17:29
-
-
Save dimmduh/9b83dc42aa687550df1d0aaf94243c68 to your computer and use it in GitHub Desktop.
Unity Texture2D json.net serialization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
jsonSerializerSettings = JsonConvert.DefaultSettings.Invoke(); | |
jsonSerializerSettings.TypeNameHandling = TypeNameHandling.Auto; | |
jsonSerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; | |
jsonSerializerSettings.Converters.Add(new z_Texture2DJsonConverter()); | |
if (Debug.isDebugBuild || Application.isEditor) | |
jsonSerializerSettings.Formatting = Formatting.Indented; | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using Newtonsoft.Json; | |
using UnityEngine; | |
public class z_Texture2DJsonConverter : JsonConverter<Texture2D> | |
{ | |
public override void WriteJson(JsonWriter writer, Texture2D? value, JsonSerializer serializer) | |
{ | |
writer.WriteValue(value.EncodeToPNG()); | |
} | |
public override Texture2D? ReadJson(JsonReader reader, Type objectType, Texture2D? existingValue, bool hasExistingValue, JsonSerializer serializer) | |
{ | |
var str = (string) reader.Value; | |
var bytes = Convert.FromBase64String(str); | |
var texture = new Texture2D(2, 2, TextureFormat.ARGB32, 0, true); | |
texture.LoadImage(bytes); | |
return texture; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment