2018年6月7日木曜日

Postprocess only assets which you selects in Unity

We can select the "ToGray" menu item, then the "Do" method is called.
The OnPostprocessTexture method will do postprocessing to only assets which were preprocessed by "Do".
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

public class ToGrayTexture : AssetPostprocessor
{
    private static List<string> guids_ = new List<string>(8);

    [MenuItem("Assets/Texture/ToGray")]
    private static void Do()
    {
        guids_.Clear();
        Object[] objects = Selection.objects;
        if(objects.Length <= 0) {
            return;
        }
        foreach(Object obj in objects) {
            string guid = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(obj));
            guids_.Add(guid);
        }
        EditorApplication.ExecuteMenuItem("Assets/Reimport");
    }


    void OnPostprocessTexture(Texture2D texture)
    {
        string guid = AssetDatabase.AssetPathToGUID(assetPath);
        if(!guids_.Exists(s => guid == s)) {
            return;
        }
        for(int i=0; i<texture.mipmapCount; ++i) {
            Color32[] colors = texture.GetPixels32(i);
            for(int j=0; j<colors.Length; ++j) {
                int c = (int)(0.299f * colors[j].r + 0.587f * colors[j].g + 0.114f * colors[j].b);
                colors[j].r = colors[j].g = colors[j].b = (byte)Mathf.Clamp(c, 0, 255);
            }
            texture.SetPixels32(colors, i);
        }
        texture.Apply();
        guids_.Remove(guid);
    }
}

0 件のコメント:

コメントを投稿