【发布时间】:2016-01-20 15:37:01
【问题描述】:
我在 Unity3D 中读取文本文件时遇到问题。 我创建了一个返回类型 float[][] 并将流读取器作为参数的方法:
public float[][] CreateWeights(StreamReader reader){
int n = 0;
float[][] Weights = new float[50][];
while((!reader.EndOfStream)){
string text = reader.ReadLine();
if (text == null)
break;
string[] strFloats = text.Split (new char[0]);
float[] floats = new float[strFloats.Length];
for(int i = 0; i<strFloats.Length; i++){
floats[i] = float.Parse(strFloats[i]);
}
Weights[n] = floats;
n++;
}
return Weights;
}
我在 void Start() 中使用这个方法来创建“权重”:
float[][] WeightsIH;
float[][] WeightsHO;
void Start(){
FileInfo theSourceFile = new FileInfo(Application.dataPath + "/Resources/WeightsIH.txt");
StreamReader reader = theSourceFile.OpenText();
FileInfo theSourceFile2 = new FileInfo(Application.dataPath + "/Resources/WeightsHO.txt");
StreamReader reader2 = theSourceFile2.OpenText();
WeightsIH = CreateWeights(reader);
WeightsHO = CreateWeights(reader2);
Yhidden = new float[50][];
HiddenOutput = new float[50][];
Xoutput = new float[1];
}
这在 Unity 的播放模式下可以正常工作。但是,在创建可执行文件后,将找不到文件,我确实理解。所以为了让它工作,我知道我需要使用 Resources.Load 并且我有:
void Start(){
TextAsset text1 = Resources.Load("WeightsIH") as TextAsset;
TextAsset text2 = Resources.Load("WeightsHO") as TextAsset;
WeightsIH = CreateWeights(text1);
WeightsHO = CreateWeights(text2);
Yhidden = new float[50][];
HiddenOutput = new float[50][];
Xoutput = new float[1];
}
当然参数类型不能再是streamReader了,我把它改成了TextAsset作为参数。以下是它的变化:
public float[][] CreateWeights(TextAsset textAsset){
float[][] Weights = new float[50][];
string[] linesFromFile = textAsset.text.Split("\n"[0]);
for(int i = 0; i<linesFromFile.Length; i++){
string[] strFloats = linesFromFile[i].Split (new char[0]);
float[] floats = new float[strFloats.Length];
for(int j = 0; j<strFloats.Length; j++){
floats[j] = float.Parse(strFloats[j]);
}
Weights[i] = floats;
}
return Weights;
}
现在这根本不起作用,甚至在播放模式下也不起作用。我会得到的运行时错误如下:
FormatException:格式无效。
System.Double.Parse (System.String s, NumberStyles 样式, IFormatProvider 提供程序) (
at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System/Double.cs:209) System.Single.Parse (System.String s) (
at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System/Single.cs:183) FollowShortestPath.CreateWeights (UnityEngine.TextAsset textAsset) (
位于 Assets/Scripts/Pathfinding/FollowShortestPath.cs:203) FollowShortestPath.Start() (
at 资产/脚本/寻路/FollowShortestPath.cs:54)
第 54 行指的是:
WeightsIH = CreateWeights(text1);
第203行指的是:
floats[j] = float.Parse(strFloats[j]);
我做错了什么?如何在可执行文件中成功读取文本文件?
【问题讨论】:
-
如您所见,我删除了我的答案。但是你能显示你正在加载和解析的文本文件吗?
-
确定:link
-
好的,我找到了。检查我的答案
标签: c# unity3d executable streamreader