我试图使用列表中第一次:-) 我在一个类中定义的列表:C#不能访问列表元素 - 参数超出范围
using UnityEngine;
using System.Collections;
using System.IO;
using UnityEditor;
using System; //This allows the IComparable Interface
using System.Collections.Generic;
public class Words : MonoBehaviour {
public List<string> wordslist = new List<string>();
static void WriteString()
{
string path = "Assets/Resources/words.txt";
//Write some text to the test.txt file
StreamWriter writer = new StreamWriter(path, true);
writer.WriteLine("Test");
writer.Close();
//Re-import the file to update the reference in the editor
AssetDatabase.ImportAsset(path);
TextAsset asset = (TextAsset)Resources.Load("words");
//Print the text from the file
Debug.Log(asset.text);
}
static void ReadString()
{
string text = " ";
string path = "Assets/Resources/words.txt";
//List<WordsList> wordslist = new List<WordsList>();
int ix = 1;
//Read the text from directly from the test.txt file
StreamReader reader = new StreamReader(path);
while(text != null){
text = reader.ReadLine();
if (text != null) {
wordslist.Add (text);
ix++;
Debug.Log (wordslist[ix].ToString());
}
}
//Debug.Log (reader.ReadToEnd().Length);
//Debug.Log(reader.ReadToEnd());
reader.Close();
}
public void GetWord(){
ReadString();
}
// Use this for initialization
void Start() {
}
// Update is called once per frame
void Update() {
}
}
我想将文本文件中的单词添加到列表中并在控制台中显示列表。 读取失败:
ArgumentOutOfRangeException:参数超出范围。
参数名:指数
我试图访问列表,因为我想添加代码从列表中选择一个随机单词这个工程
我有后正确定义它和读取值后麻烦添加功能。我没有尝试的WriteString然而,如果你看到一些错误有太多
尝试把增量这样的: 的debug.log(wordslist [IX]的ToString()); IX ++; – imsome1
您正尝试访问静态方法中的非静态字段。 –
与您当前的问题无关,但我只是想指出您遇到的大**未来**问题。此代码在构建中不起作用。如果它在Windows版本中执行,它将**从不**在移动版本上工作。您**无法写入资源文件夹,因为它是读取的。您可以读/写到适用于所有平台的'Application.persistentDataPath/YourFolder'路径。例如,请参阅[this](https://stackoverflow.com/a/40966346/3785314)。 – Programmer