Created
January 26, 2022 04:28
-
-
Save hwei/10e0d37fbfc8bbcb5257088c5b1886b5 to your computer and use it in GitHub Desktop.
How to create a custom texture importer to fix GUI alpha gamma for Unity
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 System.Reflection; | |
using UnityEditor; | |
using UnityEditor.AssetImporters; | |
using UnityEngine; | |
namespace Hwei.AssetTools | |
{ | |
[CustomEditor(typeof(TextureImporter))] | |
public class CustomTextureImporter : Editor | |
{ | |
private Editor m_DefaultEditor; | |
private TextureImporter m_Target; | |
private bool m_AlphaGammaFix; | |
private void OnEnable() | |
{ | |
var type = Type.GetType("UnityEditor.TextureImporterInspector, UnityEditor"); | |
var editor = (AssetImporterEditor) CreateEditor(target, type); | |
var setAssetImporterTargetEditor = type.GetMethod("InternalSetAssetImporterTargetEditor", BindingFlags.Instance | BindingFlags.NonPublic); | |
setAssetImporterTargetEditor.Invoke(editor, new object[] {this}); | |
m_DefaultEditor = editor; | |
m_Target = (TextureImporter) target; | |
if (string.IsNullOrEmpty(m_Target.userData)) | |
{ | |
m_AlphaGammaFix = true; | |
} | |
else | |
{ | |
var settings = JsonUtility.FromJson<GuiTextureSettings>(m_Target.userData); | |
m_AlphaGammaFix = settings.alphaGammaFix; | |
} | |
} | |
private void OnDisable() | |
{ | |
DestroyImmediate(m_DefaultEditor); | |
} | |
public override void OnInspectorGUI() | |
{ | |
if (m_Target.textureType == TextureImporterType.Sprite) | |
{ | |
EditorGUILayout.Separator(); | |
var newValue = EditorGUILayout.Toggle("Correct Alpha gamma", m_AlphaGammaFix); | |
if (newValue != m_AlphaGammaFix) | |
{ | |
m_AlphaGammaFix = newValue; | |
m_Target.userData = JsonUtility.ToJson(new GuiTextureSettings | |
{ | |
alphaGammaFix = m_AlphaGammaFix, | |
}); | |
} | |
} | |
m_DefaultEditor.OnInspectorGUI(); | |
} | |
} | |
[Serializable] | |
internal struct GuiTextureSettings | |
{ | |
public bool alphaGammaFix; | |
} | |
internal class CorrectAlphaGamma : AssetPostprocessor | |
{ | |
private void OnPostprocessSprites(Texture2D texture, Sprite[] sprites) | |
{ | |
if (string.IsNullOrEmpty(assetImporter.userData)) | |
return; | |
var settings = JsonUtility.FromJson<GuiTextureSettings>(assetImporter.userData); | |
if (!settings.alphaGammaFix) | |
return; | |
Debug.Log("Modify Texture here, reference to https://docs.unity3d.com/ScriptReference/AssetPostprocessor.OnPostprocessTexture.html"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment