Skip to content

Instantly share code, notes, and snippets.

@dimmduh
Created April 7, 2021 17:29
Show Gist options
  • Save dimmduh/9b83dc42aa687550df1d0aaf94243c68 to your computer and use it in GitHub Desktop.
Save dimmduh/9b83dc42aa687550df1d0aaf94243c68 to your computer and use it in GitHub Desktop.
Unity Texture2D json.net serialization
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;
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