UnityEditor拡張 指定した拡張子のAssetを削除する
さて、UnityEditor拡張をする機会があったため残しておこうかと
今回は、指定した拡張子のAssetの削除をEditor拡張で行います。
早速ですが、以下がソースコードです。
using UnityEngine; using UnityEditor; using System.IO; using System.Collections; using System.Collections.Generic; //UnityEditor上でWindowを表示するためEditorWindowクラスを継承します。 public class DeleteResource : EditorWindow { public static List<string>log; [MenuItem("Assets/Delete Resource Asset")] //EditorでDelete Resource Assetを選択するとProcess()が呼ばれます。 static void Process(){ log = new List<string> ();
//削除したい拡張子を指定します。 string[] searchTarget = {".prefab", ".cs"}; EditorWindow.GetWindow<DeleteResource>();
//削除したいフォルダまでのパスを指定します。 string folderPath = Application.dataPath + "/Resources/DeleteAsset";
//フォルダがあるか確認します。 if(!Directory.Exists(folderPath)){
log.Add("folder is missing"); return; }
//フォルダにあるファイルを一括で取得します。 string[] files = Directory.GetFiles (folderPath); foreach(string filePath in files){ foreach(string search in searchTarget){ if(search.Equals(System.IO.Path.GetExtension(filePath))){ File.SetAttributes (filePath, FileAttributes.Normal); File.Delete (filePath);
//Assetの変更を適応する。
AssetDatabase.Refresh();
//削除したファイルをWindowに表示するためListに追加します。 log.Add(filePath); } } } } void OnGUI(){ if(log != null){ if(log.Count != 0){ foreach(string l in log){
//Windowに文字を表示します。 EditorGUILayout.LabelField (l); } } } } }
まず、Assetsフォルダ配下にEditorフォルダを作成して、DeleteResource.csを作り上記のソースコードを記述してください。また、Resourcesフォルダを作成して配下にDeleteAssetフォルダも作成してください。
そして、DeleteAssetフォルダに今回は.prefabと.csを削除するため、削除するAssetを作成しましょう。
そして、早速削除しちゃいましょう。UnityEditorのメニューバーのAssetsの配下にDelete Resource Assetが現れていると思います。
クリックしましょう。
新たにWindowが出てきましたか?
削除したAssetのPathが表示されて、Assetがきちんと消えましたか?消えたら成功です。
以上がUnityEditor拡張で指定した拡張子のAssetを削除する方法です。
UnityEditor拡張は何かと便利に使える可能性を感じれたので、今後も触っていこうと思います。