Skip to content

Instantly share code, notes, and snippets.

@zxzsaga
Last active April 12, 2019 03:04
Show Gist options
  • Select an option

  • Save zxzsaga/c6e4277bfb890a1866b21882b506f869 to your computer and use it in GitHub Desktop.

Select an option

Save zxzsaga/c6e4277bfb890a1866b21882b506f869 to your computer and use it in GitHub Desktop.
using System.IO;
using UnityEngine;
using UnityEditor;
public class TexturePackUtility : ScriptableObject {
public Texture2D[] alphaTextures;
public string outputPath = "Assets/Textures/Topography/Topography.png";
public Material material;
public string vectorPrefix = "_Rect";
public void Pack() {
int textureCount = alphaTextures.Length;
if (textureCount == 0) {
return;
}
int size = Mathf.CeilToInt(Mathf.Sqrt(textureCount)) * alphaTextures[0].width;
Texture2D atlas = new Texture2D(size, size);
Rect[] rects = atlas.PackTextures(alphaTextures, 0, size);
File.WriteAllBytes(outputPath, atlas.EncodeToPNG());
if (!string.IsNullOrEmpty(vectorPrefix)) {
for (int i = 0, length = rects.Length; i < length; i++) {
material.SetVector(vectorPrefix + i, new Vector4(rects[i].x, rects[i].y, rects[i].width, rects[i].height));
}
}
}
}
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(TexturePackUtility))]
public class TexturePackUtilityEditor : Editor {
public override void OnInspectorGUI() {
base.OnInspectorGUI();
TexturePackUtility instance = (TexturePackUtility)target;
if (GUILayout.Button("Pack Textures")) {
instance.Pack();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment