I have read around and it seems the best way to use a text file like a hashtable is with a generic dictionary. Of course, easier said than done. There are plenty of examples on parsing text files, but none on passing them into a dictionary that I have found.
I have cobbled together some code from the limited information/examples that exist on Javascript dictionaries. It doesn’t work , but I’m not sure why. I can get the code to compile without errors, so I assume the syntax is OK(if conceptually incorrect/incomplete), but it fails to find the key/value pairs in the dictionary. Error message is
KeyNotFoundException: The given key was not present in the dictionary.
I suspect there might be two errors: one in how I understand splitting the text file into arrays, and another in how I understand adding/fetching key/value pairs in a dictionary.
I am a novice, so please excuse some of my ignorance. Any advice would be appreciated. Code is below:
Text file is just this:
NUMA*One
NUMB*Two
NUMC*Three
NUMD*4
NUME*Five
NUMF*Six
NUMG*7
NUMH*Eight
Code attached to GameObject is:
#pragma strict
import System.Collections.Generic;
/* Load the text file */
var textFile : TextAsset;
/* Create an dictionary for the values in the file */
var textInfo = new Dictionary.<String,String>();
function Start () {
/* split the text file up by newline characters */
var textLines : String [] = textFile.text.Split("/n"[0]);
/* loop through each line in the file */
for ( var thisLine : String in textLines ) {
/* split each line by asterisks into array of two variables*/
var valueString : String [] = thisLine.Split("*"[0]);
/* add the two variables in the array into the dictionary as a key and value*/
textInfo.Add(valueString[0], valueString[1]);
}
}
function Update () {
}
function OnGUI () {
/* make a labelled box to show a string pulled from dictionary by key*/
GUI.Box (Rect (10,10,80,80), textInfo["NUMB"]);
}
Thanks!