Dictionary 在unity3d中添加字典时引用为空
我正在字典中添加一个文本文件,但它给出了错误NullReferenceException:对象引用未设置为对象的实例Dictionary 在unity3d中添加字典时引用为空,dictionary,unity3d,unityscript,Dictionary,Unity3d,Unityscript,我正在字典中添加一个文本文件,但它给出了错误NullReferenceException:对象引用未设置为对象的实例 original File aa aah aahed aahing aahs aal aalii aaliis aals 代码: 导入System.Collections.Generic; 进口系统; var MytextAsset:TextAsset; 我的字典:字典。; 函数启动(){ /*按换行符拆分文本文件*/ var textLines:String[]=Mytex
original File
aa
aah
aahed
aahing
aahs
aal
aalii
aaliis
aals
代码:
导入System.Collections.Generic;
进口系统;
var MytextAsset:TextAsset;
我的字典:字典。;
函数启动(){
/*按换行符拆分文本文件*/
var textLines:String[]=MytextAsset.text.Split(“/rn”[0]);
添加(文本行[0],文本行[0]);
}
错误在最后一行。虽然我不确定您是否真的在这里使用C,但您很可能需要使用
字典的新实例初始化myDictionary
。试试像这样的东西
var myDictionary :Dictionary.<String,String> = new Dictionary.<String, String>();
var myDictionary:Dictionary.=新字典(;
您只需要在使用字典之前实例化它,在使用Add()之前在开始时这样做,您应该一帆风顺。这是一个我刚刚在unity中使用您的文件示例运行的工作示例。我刚刚编辑了一个循环,您需要将所有行添加到myDictionary
对象中:
import System.Collections.Generic;
import System.Linq;
var MytextAsset:TextAsset;
var myDictionary :Dictionary.<String,String>;
function Start () {
/* split the text file up by newline characters */
var textLines : String [] = MytextAsset.text.Split("\n"[0]);
myDictionary = new Dictionary.< String, String >() ;
for(index = 0 ; index < textLines.length ; ++index){
myDictionary.Add(textLines[index],textLines[index]);
}
for(index = 0 ; index < myDictionary.Count; ++index){
Debug.Log(myDictionary.Item[textLines[index]]);
}
}
导入System.Collections.Generic;
进口系统;
var MytextAsset:TextAsset;
我的字典:字典。;
函数启动(){
/*按换行符拆分文本文件*/
var textLines:String[]=MytextAsset.text.Split(“\n”[0]);
myDictionary=新字典。();
对于(索引=0;索引
我不确定这是否是C。我只是猜测,请随意重新标记。代码很熟悉,但C不使用那样的冒号。我不知道那是什么。我也用unity3d做了标记-希望有人能用正确的标记编辑它。你的代码文件的文件扩展名是什么?非常感谢你现在的帮助,它正在添加值,但当我想通过键访问任何值时,它会给出错误键NotFound,这取决于你使用什么来设置键。由于您的原始代码反映了您的密钥等于该值,这有点多余。您希望如何访问该值?您希望使用哪种类型的键?我希望使用列表中的单词作为键,这样当我们搜索单词时,它会告诉我们它是否有效。如果是这样,为什么不将它们存储在列表或数组中,而在找到字符串时只返回true?
import System.Collections.Generic;
import System.Linq;
var MytextAsset:TextAsset;
var myDictionary :Dictionary.<String,String>;
function Start () {
/* split the text file up by newline characters */
var textLines : String [] = MytextAsset.text.Split("\n"[0]);
myDictionary = new Dictionary.< String, String >() ;
for(index = 0 ; index < textLines.length ; ++index){
myDictionary.Add(textLines[index],textLines[index]);
}
for(index = 0 ; index < myDictionary.Count; ++index){
Debug.Log(myDictionary.Item[textLines[index]]);
}
}