昨天把项目打包发布在安卓平台时,发现一个功能的效果出错了。排查以后,发现是使用以前用的C#读取Excel的工具类ExcelReader读出来的数据是空的。(https://blog.csdn.net/KeeeepGO/article/details/83186377)
原因是在安卓平台上不能直接使用
string filePath = Application.streamingAssetsPath + "/" + excel_name;
FileStream fs = File.Open(filePath + excel_name, FileMode.Open, FileAccess.Read);
来读取Application.streamingAssetsPath的文件。
根据stackoverflow的说法,在安卓平台,必须通过WWW来读取Application.streamingAssetsPath的文件。(https://answers.unity.com/questions/1225077/using-streamingassets-in-android.html)
然而,WWW是个异步的,而我的工具类静态的,一运行就崩溃。
filePath = Application.streamingAssetsPath + "/" + excel_name;
WWW reader = new WWW(filePath);
while (!reader.isDone) { }
filePath = Application.streamingAssetsPath + "/";
于是,我掏出了另一个工具类TaskeManager(就是创建一个GameObject,通过它来使用协程)。
然而,WWW读出来的是text或者bytes怎么办嘞,我这依赖的Excel库的ExcelReaderFactory.CreateOpenXmlReader只能用Stream类型作为参数呀。
于是,我把读出来的bytes写进Application.persistentDataPath。这个路径的文件是不用www,可直接读写的。
static IEnumerator copyFileToPersistent(string filePath,string excel_name)
{
string path = Application.persistentDataPath + "/" + excel_name;
WWW www = new WWW(filePath);
if (!File.Exists(path))
{
yield return www;
if (www.error == null)
{
File.WriteAllBytes(path, www.bytes);
}
}
}
public static List<T> ReadFromExcel<T>(this List<T> current, string excel_name = "", string sheet_name = "") where T : ExcelData, new()
{
string filePath =
Application.streamingAssetsPath + "/" + excel_name;
Task task = new Task(copyFileToPersistent(filePath, excel_name));
task.Start();
while (!File.Exists(Application.persistentDataPath + "/" + excel_name))
{ }
filePath = Application.persistentDataPath + "/";
然而,还是不行。
可能是因为这个Excel库不能在安卓平台使用?(https://blog.csdn.net/yupu56/article/details/50580277)
尝试在安卓系统运行环境打断点调试看看,然而可能机子不行,unity无限卡build。
暂时先用着上面那篇博客说的方法吧。