Unity实战篇:读取Excel数据,并实现Asset数据持久化(不依赖Excel)

版权声明:转载请注明出处!不注明也无所谓,嘿嘿。 https://blog.csdn.net/qq_15020543/article/details/83098127

在开发游戏过程中我们不可避免的会遇到要给游戏数据配表的问题,(毕竟一个一个string写太累了啊喂!),而且配表还有利于数据的观察和策略性修改,也有利于游戏的维护与更新。这篇博客讲的是读取Excel表格数据,并且转化为Asset文件

它具有以下优点

  • 我们可以不用将Excel文件放到工程里,只需要生成一次Asset文件即可删除
  • 解决了项目打包成EXE文件无法读取Excel表格的问题
  • 解决了项目打包成安卓平台无法读取Excel表格的问题
  • 不需要考虑跨平台问题

以下内容部分参考自这位大神博客,我在其基础上加以细节说明。(大神们总是这样,不够体谅我这种菜鸡的感受。)

先放一下表结构图和生成的Asset图

然后开始实现

1.下载读取Excel文件必要的dll文件。

https://download.csdn.net/download/qq_15020543/10725145

把下载的三个dll文件放到Unity的Plugins文件夹下面,如果没有就创建。

2.创建Excel文件,名称随意。我们这里取名为Demo,注意后缀一定是xlsx,放在Excel文件夹下面

3.创建名为Item和ItemManager的代码(随意),但是注意,你的文件名要和类名相对应,并且下面的ExcelReader里的Item和ItemManager要改为你的类名。不然最后生成Asset的Script会为MISS

using UnityEngine;

namespace Data
{
    //这里根据自己的表结构来

    [System.Serializable]
    public class Item
    {
        public string itemId;
        public string itemLink;
        public string itemDamage;
    }

}

 

using UnityEngine;
using UnityEditor;

namespace Data
{
    [System.Serializable]
    public class ItemManager : ScriptableObject
    {
        public Item[] dataArray;
    }
}

创建代码名为ExcelReader(随意),读取Excel文件,并做编辑器拓展,转化成Asset文件。注意一定要放在Editor文件夹下面!!!

using System.Collections;
using System.Collections.Generic;
using System.Data;
using Excel;
using System.IO;
using UnityEngine;
using UnityEditor;
using Data;


public class ExcelReader  {



    public class ExcelConfig
    {
        /// <summary>
        /// 存放excel表文件夹的的路径,本例xecel表放在了"Assets/Excels/"当中
        /// </summary>
        public static readonly string excelsFolderPath = Application.dataPath + "/Excels/";

        /// <summary>
        /// 存放Excel转化CS文件的文件夹路径
        /// </summary>
        public static readonly string assetPath = "Assets/Resources/";
    }

    public class ExcelTool
    {

        /// <summary>
        /// 读取表数据,生成对应的数组
        /// </summary>
        /// <param name="filePath">excel文件全路径</param>
        /// <returns>Item数组</returns>
        public static Item[] CreateItemArrayWithExcel(string filePath)
        {
            //获得表数据
            int columnNum = 0, rowNum = 0;
            DataRowCollection collect = ReadExcel(filePath, ref columnNum, ref rowNum);

            //根据excel的定义,第二行开始才是数据
            Item[] array = new Item[rowNum - 1];
            for (int i = 1; i < rowNum; i++)
            {
                Item item = new Item();
                //解析每列的数据
                item.itemId = collect[i][0].ToString();
                item.itemLink = collect[i][1].ToString();
                item.itemDamage = collect[i][2].ToString();
                array[i - 1] = item;
            }
            return array;
        }

        /// <summary>
        /// 读取excel文件内容
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="columnNum">行数</param>
        /// <param name="rowNum">列数</param>
        /// <returns></returns>
        static DataRowCollection ReadExcel(string filePath, ref int columnNum, ref int rowNum)
        {
            FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
            IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);

            DataSet result = excelReader.AsDataSet();
            //Tables[0] 下标0表示excel文件中第一张表的数据
            columnNum = result.Tables[0].Columns.Count;
            rowNum = result.Tables[0].Rows.Count;
            return result.Tables[0].Rows;
        }
    }

    public class ExcelBuild : Editor
    {

        [MenuItem("CustomEditor/CreateItemAsset")]
        public static void CreateItemAsset()
        {
            ItemManager manager = ScriptableObject.CreateInstance<ItemManager>();
            //赋值
            manager.dataArray = ExcelTool.CreateItemArrayWithExcel(ExcelConfig.excelsFolderPath + "Demo.xlsx");

            //确保文件夹存在
            if (!Directory.Exists(ExcelConfig.assetPath))
            {
                Directory.CreateDirectory(ExcelConfig.assetPath);
            }

            //asset文件的路径 要以"Assets/..."开始,否则CreateAsset会报错
            string assetPath = string.Format("{0}{1}.asset", ExcelConfig.assetPath, "Item");
            //生成一个Asset文件
            AssetDatabase.CreateAsset(manager, assetPath);
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
        }
    }


}

4.在Unity菜单项,选择我们自定义的菜单CustomEditor->CreateItemAsset。即可生成我们需要的Asset。

5.读取使用Asset

创建另一个脚本,挂载到任意游戏物体,运行游戏。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Data;

public class DataDAO : MonoBehaviour {
    private void Start()
    {
        ItemManager manager = Resources.Load<ItemManager>("Item");
        foreach (Item i in manager.dataArray)
        {
            Debug.Log(i.itemId + "---" + i.itemLink + "---" + i.itemDamage);
        }


    }
 }

猜你喜欢

转载自blog.csdn.net/qq_15020543/article/details/83098127