我試圖使用列表中第一次:-) 我在一個類中定義的列表: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