预览
在Project视图中,扩展右键菜单,右键 – Create - Text File 创建一个Text文件,或者Lua文件。
关键点
获取当前选择的路径,以Assets路径开头
var selectPath = AssetDatabase.GetAssetPath(Selection.activeObject);
C# API 创建一个文件,并指定文件编码格式
File.WriteAllText("D:Codexxxxxx.lua", "-- test", Encoding.UTF8);
刷新Project视图中的文件
AssetDatabase.Refresh();
代码
地址:https://github.com/zhaoqingqing/blog_samplecode/blob/master/unity_helper/Editor/CreateFileEditor.cs
完整代码如下
using System.IO; using System.Text; using UnityEditor; using UnityEngine; /// <summary> /// Unity Editor 下右键创建文本类文件 /// </summary> public class CreateFileEditor : Editor { [MenuItem("Assets/Create/Lua File")] static void CreateLuaFile() { CreateFile("lua"); } [MenuItem("Assets/Create/Text File")] static void CreateTextFile() { CreateFile("txt"); } /// <summary> /// 创建文件类的文件 /// </summary> /// <param name="fileEx"></param> static void CreateFile(string fileEx) { //获取当前所选择的目录(相对于Assets的路径) var selectPath = AssetDatabase.GetAssetPath(Selection.activeObject); var path = Application.dataPath.Replace("Assets", "") + "/"; var newFileName = "new_" + fileEx + "." + fileEx; var newFilePath = selectPath + "/" + newFileName; var fullPath = path + newFilePath; //简单的重名处理 if (File.Exists(fullPath)) { var newName = "new_" + fileEx + "-" + UnityEngine.Random.Range(0, 100) + "." + fileEx; newFilePath = selectPath + "/" + newName; fullPath = fullPath.Replace(newFileName, newName); } //如果是空白文件,编码并没有设成UTF-8 File.WriteAllText(fullPath, "-- test", Encoding.UTF8); AssetDatabase.Refresh(); //选中新创建的文件 var asset = AssetDatabase.LoadAssetAtPath(newFilePath, typeof(Object)); Selection.activeObject = asset; } }