Skip to content

Instantly share code, notes, and snippets.

@takazerker
Last active April 28, 2022 19:52
Show Gist options
  • Save takazerker/75e28c3086a0177e0d08f913be39672a to your computer and use it in GitHub Desktop.
Save takazerker/75e28c3086a0177e0d08f913be39672a to your computer and use it in GitHub Desktop.
Texture2DArray importer for Unity
using System.IO;
using UnityEngine;
using UnityEditor;
using UnityEditor.AssetImporters;
class TextureArrayJson
{
public int SerializedVersion;
public Texture2D Source;
}
[ScriptedImporter(1, FileExtension)]
class TextureArrayImporter : ScriptedImporter
{
const string FileExtension = "texarray";
const string MenuName = "Assets/Create/Texture Array Importer";
[MenuItem(MenuName)]
static void CreateTextureArrayImporter()
{
var path = AssetDatabase.GetAssetPath(Selection.activeObject);
var fileName = Path.GetFileNameWithoutExtension(path) + "." + FileExtension;
var json = new TextureArrayJson();
json.SerializedVersion = 1;
json.Source = Selection.activeObject as Texture2D;
ProjectWindowUtil.CreateAssetWithContent(fileName, EditorJsonUtility.ToJson(json));
}
[MenuItem(MenuName, true)]
static bool ValidateSelectedObject()
{
return Selection.activeObject is Texture2D;
}
public override void OnImportAsset(AssetImportContext ctx)
{
var json = new TextureArrayJson();
EditorJsonUtility.FromJsonOverwrite(File.ReadAllText(ctx.assetPath), json);
if (json.Source == null || !json.Source.isReadable)
{
ctx.LogImportError("json.Source == null || !json.Source.isReadable");
return;
}
var srcPath = AssetDatabase.GetAssetPath(json.Source);
ctx.DependsOnArtifact(srcPath);
int numSlices;
int sliceSize;
Vector2Int direction;
if (json.Source.width < json.Source.height)
{
numSlices = json.Source.height / json.Source.width;
direction = new Vector2Int(0, 1);
sliceSize = json.Source.height / numSlices;
}
else
{
numSlices = json.Source.width / json.Source.height;
direction = new Vector2Int(1, 0);
sliceSize = json.Source.width / numSlices;
}
var sourceIsLinear = false;
if (GetAtPath(srcPath) is TextureImporter texImporter)
{
sourceIsLinear = !texImporter.sRGBTexture;
}
var srcPixels = json.Source.GetPixels();
var texArr = new Texture2DArray(sliceSize, sliceSize, numSlices, json.Source.format, 0 < json.Source.mipmapCount, sourceIsLinear);
texArr.wrapMode = json.Source.wrapMode;
texArr.filterMode = json.Source.filterMode;
for (var i = 0; i < numSlices; ++i)
{
var dstPixels = texArr.GetPixels(i);
for (var y = 0; y < sliceSize; ++y)
{
for (var x = 0; x < sliceSize; ++x)
{
var srcX = direction.x * sliceSize * i + x;
var srcY = direction.y * sliceSize * i + y;
dstPixels[x + y * sliceSize] = srcPixels[srcX + srcY * json.Source.width];
}
}
texArr.SetPixels(dstPixels, i);
}
texArr.Apply(true);
ctx.AddObjectToAsset("Imported Texture", texArr);
ctx.SetMainObject(texArr);
}
}
@Daniel-Dobson
Copy link

Good job.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment