您现在的位置是:首页 > 文章详情

Unity Editor 下创建Lua和Text文件

日期:2018-04-11点击:976



预览

在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;
    }
}
复制代码


原文链接:https://yq.aliyun.com/articles/352766
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章