我在Unity3D中读取文本文件时遇到了困难。我已经创建了一个方法,它返回一个类型浮点数并以一个流读取器作为参数:
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 ()中使用这个方法来创建“权重”:
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];
}这在团结的游戏模式下会很好。但是,在创建可执行文件之后,将找不到这些文件,我确实理解这一点。因此,为了使它工作,我理解我需要使用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 provider) ( 在/Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System/Double.cs:209) System.Single.Parse (System.String s) ( 在/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 () ( 在Assets/Scripts/Pathfinding/FollowShortestPath.cs:54)
第54行指:
WeightsIH = CreateWeights(text1);第203行提到:
floats[j] = float.Parse(strFloats[j]);我做错了什么?如何在可执行文件中成功读取文本文件?
发布于 2016-01-20 15:53:13
您遇到的问题是正在加载的文本文件格式。
如果你有很多空白
string[] strFloats = text.Split (new char[0]);将导致某些字符串为空。
若要解决此问题,请从文本文件中删除额外的空格,或使用:
for(int j = 0; j<strFloats.Length; j++){
if (string.IsNullOrEmpty (strFloats [j]))
continue;
floats[j] = float.Parse(strFloats[j]);
}https://stackoverflow.com/questions/34904243
复制相似问题