Last active
May 18, 2023 03:07
-
-
Save MrJul/1042aa75493a58ceeb6d2fa7d7d039c3 to your computer and use it in GitHub Desktop.
Pre-multiply alpha channel when importing Unity textures
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Using Noesis?