unity window保存文件和读取的方法

直接上代码`在这里插入代码片using UnityEngine;
using System.Runtime.InteropServices;
using System;

/// <summary>
/// 文件控制脚本
/// </summary>
public class ChinarFileController : MonoBehaviour
{
private void Update()
{
    if (Input.GetKeyDown(KeyCode.W))
    {
        Debug.Log("打开项目");
        OpenProject();
    }
    if (Input.GetKeyDown(KeyCode.S))
    {
        Debug.Log("保存项目文件");
        SaveProject();
    }
}
/// <summary>
/// 打开项目
/// </summary>
public void OpenProject()
{
    OpenFileDlg pth = new OpenFileDlg();
    pth.structSize = Marshal.SizeOf(pth);
    pth.filter = "All files (*.*)|*.*";
    pth.file = new string(new char[256]);
    pth.maxFile = pth.file.Length;
    pth.fileTitle = new string(new char[64]);
    pth.maxFileTitle = pth.fileTitle.Length;
    pth.initialDir = Application.dataPath.Replace("/", "\\") + "\\Resources"; //默认路径
    pth.title = "打开项目";
    pth.defExt = "dat";
    pth.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000200 | 0x00000008;
    if (OpenFileDialog.GetOpenFileName(pth))
    {
        string filepath = pth.file; //选择的文件路径;  
        Debug.Log(filepath);
    }
}
/// <summary>
/// 保存文件项目
/// </summary>
public void SaveProject()
{
    SaveFileDlg pth = new SaveFileDlg();
    pth.structSize = Marshal.SizeOf(pth);
    pth.filter = "All files (*.*)|*.*";
    pth.file = new string(new char[256]);
    pth.maxFile = pth.file.Length;
    pth.fileTitle = new string(new char[64]);
    pth.maxFileTitle = pth.fileTitle.Length;
    pth.initialDir = Application.dataPath; //默认路径
    pth.title = "保存项目";
    pth.defExt = "dat";
    pth.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000200 | 0x00000008;
    if (SaveFileDialog.GetSaveFileName(pth))
    {
        string filepath = pth.file; //选择的文件路径;  
        Debug.Log(pth.initialDir);
        Debug.Log(filepath);
    }
}}

这是挂在物体上的脚本

using System.Runtime.InteropServices;
using System;


/// <summary>
/// 文件日志类
/// </summary>
// [特性(布局种类.有序,字符集=字符集.自动)]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public class ChinarFileDlog
{
    public int structSize = 0;
    public IntPtr dlgOwner = IntPtr.Zero;
    public IntPtr instance = IntPtr.Zero;
    public String filter = null;
    public String customFilter = null;
    public int maxCustFilter = 0;
    public int filterIndex = 0;
    public String file = null;
    public int maxFile = 0;
    public String fileTitle = null;
    public int maxFileTitle = 0;
    public String initialDir = null;
    public String title = null;
    public int flags = 0;
    public short fileOffset = 0;
    public short fileExtension = 0;
    public String defExt = null;
    public IntPtr custData = IntPtr.Zero;
    public IntPtr hook = IntPtr.Zero;
    public String templateName = null;
    public IntPtr reservedPtr = IntPtr.Zero;
    public int reservedInt = 0;
    public int flagsEx = 0;
}

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public class OpenFileDlg : ChinarFileDlog
{
}

public class OpenFileDialog
{
    [DllImport("Comdlg32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
    public static extern bool GetOpenFileName([In, Out] OpenFileDlg ofd);
}

public class SaveFileDialog
{
    [DllImport("Comdlg32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
    public static extern bool GetSaveFileName([In, Out] SaveFileDlg ofd);
}

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public class SaveFileDlg : ChinarFileDlog
{
}

这是方便写入路径的类
代码直接放进unity力就可以用

<think>好的,我现在要在Unity中实现读取xlsx文件的功能,需要怎么做呢?首先,用户提到了使用插件或者脚本,我记得之前有听说过NPOI这个插件,可以用来处理Excel文件。不过具体步骤可能不太清楚,得一步步理清楚。 首先,可能需要安装NPOI插件到Unity项目中。应该是在Asset Store或者GitHub上找到这个插件,然后导入到项目里。不过需要注意插件的兼容性,是否支持Unity的版本,还有是否支持xlsx格式,因为有些插件可能只处理旧版的xls文件。 安装好插件之后,应该要创建脚本来读取Excel文件。可能需要用到NPOI的命名空间,比如使用HSSFXSSF来处理不同的Excel格式。例如,XSSFWorkbook用于xlsx文件,HSSFWorkbook用于xls文件。然后,通过文件读取Excel文件,遍历每个工作表行,获取单元格的数据。 然后,用户可能需要将读取的数据转换成游戏中的数据格式,比如存储在ScriptableObject或者生成CS文件。比如引用中提到导出为cs文件的好处是游戏运行时自动加载,方便通过字典访问。不过这样会增加内存消耗,需要权衡利弊。 接下来,可能要考虑在编辑器下扩展功能,比如添加一个菜单项,点击后自动读取Excel并生成对应的C#类或者数据结构。这涉及到Unity的Editor脚本,需要使用UnityEditor命名空间,并且将脚本放在Editor文件夹下。 另外,处理Excel文件时需要注意数据类型转换,比如文本、数字、日期等,可能需要不同的处理方式。还要处理空单元格或者格式错误的情况,避免运行时出错。 还有,用户提到使用TextAsset来读取文本文件,但Excel是二进制格式,不能直接用TextAsset。所以必须通过插件或者第三方库来解析。引用中的代码示例展示了如何引用TextAsset,但可能只是用于存储路径或其他元数据,实际处理还是需要NPOI。 最后,测试读取功能是否正常,确保在不同平台下的兼容性,比如在WindowsMac上是否都能正确读取xlsx文件。可能需要处理文件路径的问题,使用Application.dataPath或者StreamingAssets路径来定位Excel文件的位置。 总结一下步骤应该是:导入NPOI插件→编写读取脚本→处理数据转换→生成所需格式(如CS文件)→编辑器扩展方便使用→测试功能。过程中需要注意错误处理、内存管理跨平台兼容性。</think>在 Unity读取 xlsx 文件,推荐使用 **NPOI 插件**实现跨平台解析。以下是具体实现步骤: --- ### 一、安装 NPOI 插件 1. 下载 [NPOI 插件](https://archive.codeplex.com/?p=npoi) 的 Unity 兼容版本(需支持 .NET Standard 2.0) 2. 将插件文件(`ICSharpCode.SharpZipLib.dll`、`NPOI.dll` 等)放入 Unity 项目的 `Plugins` 文件夹 --- ### 二、编写读取脚本 ```csharp using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; // 针对 xlsx 格式 using System.IO; using UnityEngine; public class ExcelReader : MonoBehaviour { public TextAsset excelFile; // 拖入xlsx文件到Inspector void Start() { using (var stream = new MemoryStream(excelFile.bytes)) { IWorkbook workbook = new XSSFWorkbook(stream); // 创建xlsx工作簿 ISheet sheet = workbook.GetSheetAt(0); // 读取第一个工作表 // 遍历行(跳过表头) for (int rowIdx = 1; rowIdx <= sheet.LastRowNum; rowIdx++) { IRow row = sheet.GetRow(rowIdx); if (row == null) continue; // 读取单元格数据 string id = row.GetCell(0)?.ToString(); string name = row.GetCell(1)?.ToString(); Debug.Log($"ID: {id}, Name: {name}"); } } } } ``` --- ### 三、生成结构化数据(以 ScriptableObject 为例) 1. 创建数据容器类: ```csharp [CreateAssetMenu(fileName = "ExcelData", menuName = "Data/ExcelData")] public class ExcelData : ScriptableObject { public List<CardData> cardList = new List<CardData>(); } [System.Serializable] public class CardData { public int id; public string name; public float attack; } ``` 2. 扩展编辑器工具生成数据: ```csharp #if UNITY_EDITOR using UnityEditor; using NPOI.SS.UserModel; public class ExcelImporter : EditorWindow { [MenuItem("Tools/Import Excel")] static void Import() { string path = EditorUtility.OpenFilePanel("Select Excel", Application.dataPath, "xlsx"); if (!string.IsNullOrEmpty(path)) { IWorkbook workbook = WorkbookFactory.Create(path); ISheet sheet = workbook.GetSheetAt(0); ExcelData data = ScriptableObject.CreateInstance<ExcelData>(); for (int i = 1; i <= sheet.LastRowNum; i++) { IRow row = sheet.GetRow(i); data.cardList.Add(new CardData(){ id = int.Parse(row.GetCell(0).ToString()), name = row.GetCell(1).ToString(), attack = float.Parse(row.GetCell(2).ToString()) }); } AssetDatabase.CreateAsset(data, "Assets/Data/ExcelData.asset"); AssetDatabase.SaveAssets(); } } } #endif ``` --- ### 四、优化建议 1. **内存管理**:通过 ScriptableObject 动态加载/卸载数据,避免全部常驻内存[^1] 2. **缓存机制**:对频繁读取的数据建立 Dictionary 索引 3. **异常处理**:添加 try-catch 块处理格式错误 4. **多平台适配**:将 xlsx 文件放在 `StreamingAssets` 文件夹实现跨平台路径访问 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值