方便策划在Unity中直接使用Excel配置数据,
核心是ScriptableObject类型,
不会将Excel相关内容打包,
实现编辑器中即时替换.
思维导图:
脚本:
ExcelAccess:(转换Excel数据)
using UnityEngine;
using Excel;
using System.Data;
using System.IO;
using System.Collections.Generic;public class ExcelAccess
{
public static string Excel = "Item";//查询item表
public static List<Item> SelectItemTable()
{
string excelName = Excel + ".xlsx";
string sheetName = "sheet1";
DataRowCollection collect = ExcelAccess.ReadExcel(excelName, sheetName);List<Item> itemArray = new List<Item>();
for (int i = 1; i < collect.Count; i++)
{
if (collect[i][1].ToString() == "") continue;
//Debug.Log(collect[i][3].GetType());//会自动判断类型
Item item = new Item
{
m_Id = collect[i][0].ToString(),
m_count = collect[i][1].ToString(),
m_gold = collect[i][2].ToString(),
m_name = collect[i][3].ToString()
};
itemArray.Add(item);
}
return itemArray;
}// 读取 Excel ; 需要添加 Excel.dll; System.Data.dll;
// excelName>excel文件名,sheetName>sheet名称
static DataRowCollection ReadExcel(string excelName, string sheetName)
{
//Assets下面的相对路径,打开读取存为文件流
//FileStream读取出来的是字节数组,然后通过编码转换将字节数组转换成字符串
//使用Excel的数据格式读取并转换文件流
string path = Application.dataPath + "/ExcelTest/" + excelName;
FileStream stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read);
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);DataSet result = excelReader.AsDataSet();
//tables就是sheet的数组,本身已经是一个存储了数据的二维数组
//Excel文档下面千万不要有空格之后的内容,不然也算作行列,会计算错误,全家爆炸
int columns = result.Tables[0].Columns.Count;
int rows = result.Tables[0].Rows.Count;//返回DataRow的集合
//tables可以按照sheet名获取,也可以按照sheet索引获取
//return result.Tables[0].Rows;//同下
return result.Tables[sheetName].Rows;
}
}
BuildAsset:(构建本地化功能)
using UnityEngine;
using UnityEditor;//利用ScriptableObject创建资源文件
public class BuildAsset : Editor
{//Excel数据转化至本地,菜单栏执行功能创建
[MenuItem("BuildAsset/Build Scriptable Asset")]
public static void ExcuteBuild()
{
ItemHolder holder = ScriptableObject.CreateInstance<ItemHolder>();//查询excel表中数据,赋值给asset文件
holder.items = ExcelAccess.SelectItemTable();string path = "Assets/Resources/ExcelToScriptableObject/ItemHolder.asset";
AssetDatabase.CreateAsset(holder, path);
AssetDatabase.Refresh();Debug.Log("BuildAsset Success!");
}
}
ItemHolder:(一个ScriptableObject类)
using UnityEngine;
using System.Collections.Generic;//基于ScriptObject的BookHolder类
public class ItemHolder : ScriptableObject
{
public List<Item> items;
}
Item:(一个承接数据的类)
//道具实体类
[System.Serializable]
public class Item
{
public string m_Id;
public string m_count;
public string m_gold;
public string m_name;
}
ReadItemHolders:(读取数据)
using UnityEngine;
//读取booknames的scriptObject文件
//使用Resources直接读取
public class ReadItemHolders : MonoBehaviour
{
//相对路径
readonly string assetName = "ExcelToScriptableObject/ItemHolder";void Start()
{
ItemHolder asset = Resources.Load<ItemHolder>(assetName);
foreach (Item gd in asset.items)
{
Debug.Log(gd.m_Id);
Debug.Log(gd.m_count);
Debug.Log(gd.m_gold);
Debug.Log(gd.m_name);
}
}
}