2017-08-16 37 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

我的意思是,如果这个方法只是为了这个类的目的而被调用,静态并放弃额外的参数。 –