Unity Editor 下創建Lua和Text文件


預覽

在Project視圖中,擴展右鍵菜單,右鍵Create - Text File 創建一個Text文件,或者Lua文件。

imageimage

關鍵點

獲取當前選擇的路徑,以Assets路徑開頭

var selectPath = AssetDatabase.GetAssetPath(Selection.activeObject);

 

C# API 創建一個文件,並指定文件編碼格式

File.WriteAllText("D:\Code\xxx\xxx.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;
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM