博客
关于我
UnityEditor编辑器扩展开发_SaveDialog保存到目录代码实现
阅读量:529 次
发布时间:2019-03-08

本文共 4226 字,大约阅读时间需要 14 分钟。

打开目录和保存文件的实现

在 Unity 项目中,通过创建自定义对话框可以实现便捷的文件操作。以下是实现从文件夹到本地资源文件夹的克隆夹门方法。

必要工具

无需依赖 UnityEditor 模块,可以通过 Windows API 实现文件夹操作。

实现步骤

  • 创建对话框类

    using System;using System.IO;using System.Linq;using UnityEngine;public class SaveFileDialogue : MonoBehaviour{    private string fileName;    private string savePath;    private string currentScenePath;    public void OpenSaveDialogue()    {        var savePath = EditorUtility.SaveFolderPanel("请选择要写的文件夹",/Application.dataPath + "/Resources/", "");        if (string.IsNullOrEmpty(savePath))        {            Debug.LogError("未选择保存路径...");            return;        }        fileName = $"Test_{DateTime.Now:HH-mm-dd} {Random.Range(0, 999)}.txt";        this.transform.GetComponent
    (); } public void SaveFile() { bool saveSuccess = false; try { var saveFile = new FileInfo(savePath + "/testfile.txt"); if (!saveFile.Directory.Exists( saveFile.ParentDirectory )) // 创建存储目标目录 { Directory.CreateDirectory( saveFile.ParentDirectory ); } Debug.Log("文件已成功写入..."); saveSuccess = true; } catch (Exception ex) { Debug.LogError(ex.Message); } finally { if (saveSuccess) { SceneManager.LoadScene(1); } else { Debug.Log("写入失败"); } } }}
  • 创建跨平台保存文件夹对话框

    using System;using System.Linq;using UnityEngine;public class SaveFolderPanel : MonoBehaviour{    private static string[] ExtensionList => new[] { ".png", ".jpg", ".jpeg", ".txt" }; // 可以添加其他文件类型  public void OpenFolder()  {      var path = EditorUtility.OpenFolderPanel("打开文件夹", "", "");      if (string.IsNullOrEmpty(path))      {          Debug.LogWarning("未选择目录...");          return;      }      StartCoroutine(CopyFilesToResourcesFolder(path));  }  private static IEnumerator CopyFilesToResourcesFolder(string uploadFolder)  {      var path = uploadFolder;      var resourceFolder = Application.dataPath + "/Resources/";      foreach (var file in_CBCR  Directory.GetFiles(uploadFolder))      {          if (file.EndsWithAny(SaveFolderPanel.ExtensionList))          {              var destPath = resourceFolder + file.Replace("\\", "/");              if (!Directory.Exists(resourceFolder + "/" + Path.GetFileName(destPath)))              {                  Directory.CreateDirectory(resourceFolder + "/" + Path.GetFileName(destPath));              }              // 复制文件              File.Copy(file, destPath);              Debug.Log("文件" + Path.GetFileName(file) + "已被复制到资源文件夹");          }      }      yield return null;  }}
  • 3. **适用范围**- 该代码基于 Windows 系统,通过 DRS 拿文件和控制文件夹操作实现。- 把文件夹内容导出到资源文件夹中,适用于单建模场景。#### 工作原理- **文件对话框**:通过 Windows 的 `OPENFILENAME` 结构体和 `LocalDialog` 统 Tesla pressFileChooser 包裹文件选择对话框。用户选择文件后,路径返回到程序中。- **文件夹对话框**:使用 `Directory.GetFiles` 和各个文件进行根据指定扩展名进行筛选的复制操作。- **错误处理**:代码中包含 `try-catch` 语句,确保在发生异常时还有有用的信息输出。#### 性能优化- 在批量处理大量文件时,使用 `Directory.GetFiles` 可能导致性能问题。对于高文件数量可以考虑分批处理或者异步处理。#### 定制- 根据需求,可以修改保存的路径、文件类型、文件命名规则等。- 可以添加上传进度条以改善用户体验,但这可能稍微复杂一些。### 代码数字化一种整合方式:```csharpusing UnityEngine;using System;using System.IO;public class LoadAsset : MonoBehaviour{    public Transform obj;    private string fileName;     public void SaveAsset()    {        MeshFilter meshFilter = obj.GetComponent_EXPR< MeshFilter>();        if (meshFilter == null) return;        Mesh mesh = meshFilter.mesh;        var assetPath = $"Resources/{DateTime.Now:HH-mm-dd}_{Random.Range(0, 999)}.asset";        AssetDatabase.CreateAsset(mesh, "Assets/" + assetPath);        Debug.Log("资产已保存至" + assetPath + "文件");    }}

    这种写法遵循“Namespacing 不作茬”的规则,反映了使用方便的结构。

    去空行和优化

    美观化和去空行建议:

    去空行提示

    // 空行去除脚本功能       private void RemoveEmptyLines(){    foreach (var script in scripts.GetAllScriptsInFolderAsync())    {        TextAsset asset = AssetDatabase.LoadAssetAtPath
    (script.path); if (string.IsNullOrEmpty(asset)) { AssetDatabase.DeleteAsset(script.path + "/ " + system.testAsset + …); } }}

    画面优化和效率

    当导出大量资源时,可以考虑批量处理或压缩技术,以提高效率。

    最终结论

    该方案能够在编辑器中实现文件和文件夹的操作,对于最终的打包版本,只需去掉依赖脚本即可实现裁剪专家。通过自定义对话框实现文件操作,既符合程序设计规范,又保留了灵活性。

    转载地址:http://rtiiz.baihongyu.com/

    你可能感兴趣的文章
    QGIS中怎样实现数据坐标系转换
    查看>>
    PowerDesigner学习--基本步骤
    查看>>
    PowerDesigner导出Report通用报表
    查看>>
    PowerDesigner教程系列(二)概念数据模型
    查看>>
    Powerdesigner显示表的comment和列的comment的方法
    查看>>
    PowerDesigner最基础的使用方法入门学习
    查看>>
    PowerDesigner版本控制器设置权限
    查看>>
    PowerDesigner生成数据模型并导出报告
    查看>>
    QGIS中导入dwg文件并使用GetWKT插件获取绘制元素WKT字符串以及QuickWKT插件实现WKT显示在图层
    查看>>
    PowerDesigner逆向工程从SqlServer数据库生成PDM(图文教程)
    查看>>
    PowerEdge T630服务器安装机器学习环境(Ubuntu18.04、Nvidia 1080Ti驱动、CUDA及CUDNN安装)
    查看>>
    PowerPC-object与elf中的符号引用
    查看>>
    QFileSystemModel
    查看>>
    Powershell DSC 5.0 - 参数,证书加密账号,以及安装顺序
    查看>>
    PowerShell 批量签入SharePoint Document Library中的文件
    查看>>
    Powershell 自定义对象小技巧
    查看>>
    pytorch从预训练权重加载完全相同的层
    查看>>
    PowerShell~发布你的mvc网站
    查看>>
    PowerShell使用详解
    查看>>
    Powershell制作Windows安装U盘
    查看>>