Skip to content

Instantly share code, notes, and snippets.

@dimmduh
Created August 30, 2021 09:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dimmduh/4a444eb5f22a83125d6e5b00b5726fdd to your computer and use it in GitHub Desktop.
Save dimmduh/4a444eb5f22a83125d6e5b00b5726fdd to your computer and use it in GitHub Desktop.
json.net converter for Unity Texture
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