我在Unity3D中阅读文本文件时遇到问题。 我创建了一个方法,它返回一个类型float [] []并将一个streamreader作为参数:
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()中使用此方法来创建&#34;权重&#34;:
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提供者)(
在 /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()(
在 资产/脚本/寻路/ FollowShortestPath.cs:54)
第54行指的是:
WeightsIH = CreateWeights(text1);
和第203行指的是:
floats[j] = float.Parse(strFloats[j]);
我做错了什么?如何在可执行文件中成功读取文本文件?
答案 0 :(得分:1)
您遇到的问题是正在加载的文本文件格式。
Couse你有很多空格
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]);
}