前言:之前总会遇到一些资源需要复制一份到别的目录去修改的需求,但是每次操作不是要Show in Explorer再执行复制就是要Ctrl+D然后拖拽再改名,所以写了这个脚本。
![](https://img.haomeiwen.com/i18074876/15d295ddc587f430.png)
![](https://img.haomeiwen.com/i18074876/d20e93bff86e9ad3.png)
功能:
- 复制文件
- 粘贴文件
- 剪贴文件
- 项目内地址自动解析为复制
逻辑:
复制时把所有已选择文件转为unity路径数组记录,使用AssetDatabase.CopyAsset()
和AssetDatabase.MoveAsset()
来实现剪切和粘贴,也就只识别以Assets/
目录开头的路径文件或文件夹
并且在ClipboardListener类里做了剪贴板实时监听功能,会把从任何地方复制的满足unity路径的string自动放到粘贴里。
源码:
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
public class CopyPasteTool : Editor
{
public static List<string> copyPaths;
static bool isCut = false;
[MenuItem("Assets/剪切")]
static void Cut()
{
Copy();
isCut = true;
}
[MenuItem("Assets/复制")]
static void Copy()
{
if (copyPaths == null)
{
copyPaths = new List<string>();
}
string[] assetGUIDs = Selection.assetGUIDs;
copyPaths.Clear();
for (int i = 0; i < assetGUIDs.Length; i++)
{
copyPaths.Add(AssetDatabase.GUIDToAssetPath(assetGUIDs[i]));
}
isCut = false;
}
[MenuItem("Assets/粘贴")]
static void Paste()
{
for (int i = 0; i < copyPaths.Count; i++)
{
string soureName = Path.GetFileName(copyPaths[i]);
string targetPath = AssetDatabase.GUIDToAssetPath(Selection.assetGUIDs[0]);
if (Path.HasExtension(targetPath))
{
targetPath = Path.GetDirectoryName(targetPath) + @"\" + soureName;
}
else
{
targetPath += @"\" + soureName;
}
if (File.Exists(targetPath))
{
int temp = EditorUtility.DisplayDialogComplex("文件重复警告", $"当前目录存在 {soureName},是否替换", "替换", "取消", "重新命名");
switch (temp)
{
case 0:
break;
case 1:
return;
case 2:
string soureNameExtension = Path.GetFileNameWithoutExtension(copyPaths[i]);
string soureExtension = Path.GetExtension(copyPaths[i]);
targetPath = Path.GetDirectoryName(targetPath) + @"\" + soureNameExtension + "_" + soureExtension;
break;
}
}
if (isCut)
{
AssetDatabase.MoveAsset(copyPaths[i], targetPath);
isCut = false;
copyPaths.Clear();
}
else
{
AssetDatabase.CopyAsset(copyPaths[i], targetPath);
}
}
}
[MenuItem("Assets/粘贴", validate = true)]
static bool PasteCheck()
{
if (copyPaths == null || copyPaths.Count == 0)
{
return false;
}
return true;
}
}
[InitializeOnLoad]
public class ClipboardListener : CopyPasteTool
{
static ClipboardListener()
{
EditorApplication.update += OnEditorUpdate;
}
static string previousClipBoardValue;
private static void OnEditorUpdate()
{
if (GUIUtility.systemCopyBuffer != previousClipBoardValue)
{
previousClipBoardValue = GUIUtility.systemCopyBuffer;
if (File.Exists(previousClipBoardValue) && previousClipBoardValue.StartsWith("Assets"))
{
if (copyPaths == null)
{
copyPaths = new List<string>();
}
copyPaths.Clear();
copyPaths.Add(previousClipBoardValue);
}
}
}
}
网友评论