2017-08-16 35 views
0

我試圖使用列表中第一次:-) 我在一個類中定義的列表: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然而,如果你看到一些錯誤有太多

+0

嘗試把增量這樣的: 的debug.log(wordslist [IX]的ToString()); IX ++; – imsome1

+1

您正嘗試訪問靜態方法中的非靜態字段。 –

+0

與您當前的問題無關,但我只是想指出您遇到的大**未來**問題。此代碼在構建中不起作用。如果它在Windows版本中執行,它將**從不**在移動版本上工作。您**無法寫入資源文件夾,因爲它是讀取的。您可以讀/寫到適用於所有平臺的'Application.persistentDataPath/YourFolder'路徑。例如,請參閱[this](https://stackoverflow.com/a/40966346/3785314)。 – Programmer

回答

1

所有指標從0開始而不是1,所以更換

int ix = 1; 

int ix = 0; 

和移動ix++;到最後一行while -loop,所以後面:

Debug.Log (wordslist[ix]); 
ix++; 
+0

謝謝,但問題依然存在。還我有資產/腳本/ Words.cs(41,33):錯誤CS0120:一個對象引用需要訪問非靜態成員'Words.wordslist」 –

+0

@ DanielBen-Shabtay:你也移動了'IX ++'後你在哪裏使用它?否則,這將是1,如果你只是有一個導致異常一個項目,因爲'wordslist [1]'訪問的第二個項目 –

+0

是的,我已經搬到了九++後的debug.log –

0

你真的希望你ReadStringWriteString方法是靜態的嗎?有靜態方法意味着它們不依賴於你的Words類的實例,這意味着你不能使用字段wordslist,因爲這是屬於你的Words類的一個實例。

您可以傳遞的wordslist的實例作爲參數傳遞給ReadString來代替。

+0

開始我不介意將wordslist作爲參數傳遞給ReadString和WriteString。我所需要的是能夠將文本文件讀取到列表中,選擇一個隨機單詞。我不確定我會需要WriteString,我只是從示例中複製它以防萬一需要它 –

+0

我的意思是,如果這個方法只是爲了這個類的目的而被調用,靜態並放棄額外的參數。 –