博客
关于我
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/

    你可能感兴趣的文章
    MYSQL:基础——触发器
    查看>>
    Mysql:连接报错“closing inbound before receiving peer‘s close_notify”
    查看>>
    mysqlbinlog报错unknown variable ‘default-character-set=utf8mb4‘
    查看>>
    mysqldump 参数--lock-tables浅析
    查看>>
    mysqldump 导出中文乱码
    查看>>
    mysqldump 导出数据库中每张表的前n条
    查看>>
    mysqldump: Got error: 1044: Access denied for user ‘xx’@’xx’ to database ‘xx’ when using LOCK TABLES
    查看>>
    Mysqldump参数大全(参数来源于mysql5.5.19源码)
    查看>>
    mysqldump备份时忽略某些表
    查看>>
    mysqldump实现数据备份及灾难恢复
    查看>>
    mysqldump数据库备份无法进行操作只能查询 --single-transaction
    查看>>
    mysqldump的一些用法
    查看>>
    mysqli
    查看>>
    MySQLIntegrityConstraintViolationException异常处理
    查看>>
    mysqlreport分析工具详解
    查看>>
    MySQLSyntaxErrorException: Unknown error 1146和SQLSyntaxErrorException: Unknown error 1146
    查看>>
    Mysql_Postgresql中_geometry数据操作_st_astext_GeomFromEWKT函数_在java中转换geometry的16进制数据---PostgreSQL工作笔记007
    查看>>
    mysql_real_connect 参数注意
    查看>>
    mysql_secure_installation初始化数据库报Access denied
    查看>>
    MySQL_西安11月销售昨日未上架的产品_20161212
    查看>>