using UnityEditor;
using UnityEngine;
using System.IO;
public class ReplaceByFileDir : EditorWindow
{
string filePath;
Rect fileRect;
string postfixName;
string tipMsg = null;
MessageType tipMsgType = MessageType.Info;
string sourcePostfix;
[MenuItem("LuaFramework/批量修改文本后缀")]
public static void OpenWindow()
{
ReplaceByFileDir window = GetWindow<ReplaceByFileDir>(false, "批量修改文本后缀");
window.Show();
}
void OnGUI()
{
EditorGUILayout.Space();
EditorGUILayout.Space();
GUILayout.Label("文件夹路径:");
//获得一个框
fileRect = EditorGUILayout.GetControlRect(GUILayout.Width(position.width - 25));
//将上面的框作为文本输入框
filePath = EditorGUI.TextField(fileRect, filePath);
//拖拽文件中
if (Event.current.type == EventType.DragUpdated || Event.current.type == EventType.DragPerform)
{
string[] paths = DragAndDrop.paths;
if (fileRect.Contains(Event.current.mousePosition) && paths != null && paths.Length > 0)
{
if (Directory.Exists(paths[0]))
{
//更改鼠标外观
DragAndDrop.visualMode = DragAndDropVisualMode.Generic;
//拖拽丢弃时才进行赋值操作
if (Event.current.type == EventType.DragPerform)
filePath = paths[0];
}
}
}
EditorGUILayout.Space();
sourcePostfix = EditorGUILayout.TextField("源后缀名:", sourcePostfix);
postfixName = EditorGUILayout.TextField("修改为后缀名:", postfixName);
EditorGUILayout.Space();
if (GUILayout.Button("批量替换", GUILayout.Height(30)))
{
Replace();
}
EditorGUILayout.Space();
//提示信息
if (!string.IsNullOrEmpty(tipMsg))
{
EditorGUILayout.HelpBox(tipMsg, tipMsgType);
}
}
void Replace()
{
if (!Directory.Exists(filePath))
{
tipMsg = "错误路径!";
tipMsgType = MessageType.Error;
return;
}
if (string.IsNullOrEmpty(postfixName))
{
tipMsg = "文件后缀为空!";
tipMsgType = MessageType.Error;
return;
}
var dir = new DirectoryInfo(filePath);
var files = dir.GetFiles($"*.{sourcePostfix}", SearchOption.AllDirectories);
int count = 0;
int length = files.Length;
for (int i = 0; i < length; i++)
{
var path = files[i].FullName;
var metaPath = path + ".meta";
var meta = new FileInfo(metaPath);
path = path.Replace(sourcePostfix, postfixName);
metaPath = metaPath.Replace(sourcePostfix, postfixName);
files[i].MoveTo(path);
meta.MoveTo(metaPath);
}
AssetDatabase.Refresh();
AssetDatabase.SaveAssets();
tipMsg = "修改成功!修改了" + count + "个文本";
tipMsgType = MessageType.Info;
}
void UpdateProgress(int progress, int progressMax, string desc)
{
string title = "Processing...[" + progress + " - " + progressMax + "]";
float value = (float)progress / (float)progressMax;
EditorUtility.DisplayProgressBar(title, desc, value);
}
}

本文介绍了一个Unity编辑器窗口脚本,用于批量修改文件夹内文件的后缀名。该脚本允许用户通过拖拽文件夹的方式选择目标路径,并指定源后缀名及目标后缀名,实现对文件夹及其子目录下所有符合特定后缀条件的文件进行批量替换。

3162

被折叠的 条评论
为什么被折叠?



