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

    你可能感兴趣的文章
    OAuth2授权码模式详细流程(一)——站在OAuth2设计者的角度来理解code
    查看>>
    OAuth2:项目演示-模拟微信授权登录京东
    查看>>
    OA系统多少钱?OA办公系统中的价格选型
    查看>>
    OA系统选型:选择好的工作流引擎
    查看>>
    OA项目之我的会议(会议排座&送审)
    查看>>
    OA项目之我的会议(查询)
    查看>>
    Object c将一个double值转换为时间格式
    查看>>
    object detection训练自己数据
    查看>>
    object detection错误之Could not create cudnn handle: CUDNN_STATUS_INTERNAL_ERROR
    查看>>
    object detection错误之no module named nets
    查看>>
    Object of type 'ndarray' is not JSON serializable
    查看>>
    Object Oriented Programming in JavaScript
    查看>>
    object references an unsaved transient instance - save the transient instance before flushing
    查看>>
    Object.keys()的详解和用法
    查看>>
    OBJECTIVE C (XCODE) 绘图功能简介(转载)
    查看>>
    Objective-C ---JSON 解析 和 KVC
    查看>>
    Objective-C 编码规范
    查看>>
    Objective-C——判断对象等同性
    查看>>
    Objective-C之成魔之路【7-类、对象和方法】
    查看>>
    Objective-C享元模式(Flyweight)
    查看>>