Unity Editor 編輯器擴展 十二 OverWriter

項目Assets資源導入時,常常會有重複的資源多次被導入,導致項目冗餘,這裏一個小工具可以在導入時檢測,即時給你提示
這裏寫圖片描述
只需要在Editor文件中創建下列兩個腳本:

using System.IO;
using System.Text.RegularExpressions;
using UnityEditor;

public class OverwriteAsset
{
    public string originalAssetPath {
        get {
            return Path.Combine (directoryName, filename + "." + extension);
        }
    }

    public bool exists { get; private set; }

    public string filename { get; private set; }

    public string extension { get; private set; }

    private string directoryName;
    private string assetPath;
    const string pattern = "^(?<name>.*)\\s\\d+\\.(?<extension>.*)$";

    public OverwriteAsset (string assetPath)
    {
        this.assetPath = assetPath;
        directoryName = Path.GetDirectoryName (assetPath);
        var match = Regex.Match (Path.GetFileName (assetPath), pattern);

        exists = match.Success;

        if (exists) {
            filename = match.Groups ["name"].Value;
            extension = match.Groups ["extension"].Value;
        }
    }

    public void Overwrite ()
    {
        FileUtil.ReplaceFile (assetPath, originalAssetPath);
        Delete ();
        AssetDatabase.ImportAsset (originalAssetPath);
    }

    public void Delete ()
    {
        AssetDatabase.DeleteAsset (assetPath);
    }
}

using UnityEditor;
using UnityEngine;

public class Overwriter : AssetPostprocessor
{

    const string message = "\"{0}.{1}\"資源已經存在,是否更新資源?";

    static void OnPostprocessAllAssets (
        string[] importedAssets,
        string[] deletedAssets,
        string[] movedAssets,
        string[] movedFromPath)
    {
        if (Event.current == null || Event.current.type != EventType.DragPerform)
            return;

        foreach (var assetPath in importedAssets) {

            var asset = new OverwriteAsset (assetPath);

            if (asset.exists) {

                var overwriteMessage =
                    string.Format (message, asset.filename, asset.extension);

                var result = EditorUtility.DisplayDialogComplex (asset.originalAssetPath,
                    overwriteMessage,
                    "替換",
                    "保留兩者",
                    "中止");

                if (result == 0) {
                    asset.Overwrite ();
                } else if (result == 2) {
                    asset.Delete ();
                }

            }
        }
    }
}

本文鏈接:http://blog.csdn.net/WarrenMondeville/article/details/53807605

發佈了31 篇原創文章 · 獲贊 17 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章