Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@MrJul
Last active May 18, 2023 03:07
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save MrJul/1042aa75493a58ceeb6d2fa7d7d039c3 to your computer and use it in GitHub Desktop.
Save MrJul/1042aa75493a58ceeb6d2fa7d7d039c3 to your computer and use it in GitHub Desktop.
Pre-multiply alpha channel when importing Unity textures
using System;
using JetBrains.Annotations;
using UnityEditor;
using UnityEngine;
namespace UnityProject.Editor {
public sealed class TextureAlphaPremultiplier : AssetPostprocessor {
public void OnPreprocessTexture() {
if (ShouldPremultiplyAlpha())
((TextureImporter) assetImporter).alphaIsTransparency = false;
}
public void OnPostprocessTexture([NotNull] Texture2D texture) {
if (!ShouldPremultiplyAlpha())
return;
int width = texture.width;
int height = texture.height;
for (int x = 0; x < width; ++x) {
for (int y = 0; y < height; ++y) {
Color color = texture.GetPixel(x, y);
texture.SetPixel(x, y, Premultiply(color));
}
}
texture.Apply();
Debug.Log("Automatically premultiplied alpha for " + assetPath);
}
private static Color Premultiply(Color color) {
float a = color.a;
return new Color(color.r * a, color.g * a, color.b * a, a);
}
[Pure]
private bool ShouldPremultiplyAlpha() {
return assetPath.EndsWith(".png", StringComparison.OrdinalIgnoreCase);
}
}
}
@atcarter714
Copy link

Using Noesis?

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