- Home /
How can I read data from a text file, putting a large amount of data into structures
hi folks!
i want to read a large amount of text-pairs like ["foo", "bar"] into my unity-document and want it to be easy to be changed later. in the end there should be an big array holding these pairs in their sub-arrays, like [["foo", "bar"], ["foo2", "bar2"], ["foo2", "bar2"], ...]
any ideas? thnx!
Answer by duck · Apr 28, 2010 at 03:51 PM
If by "read" you mean you want to read this data from a text file, you can add a text file to your project by copying it into your assets folder.
You can then reference the file in a variable whose type is "TextAsset" (you need to drag the reference in).
Then you could parse the text using String.Split. For example, if your data file uses commas to separate items in pairs, and newline characters to separate pairs, you could use this:
Original File:
apple,ball
car,dog
egg,fish
goat,hat
Script (JS):
var dataFile : TextAsset;
function Start() {
var returnChar = "\n"[0];
var commaChar = ","[0];
var dataLines = dataFile.text.Split(returnChar);
var buildDataPairs = new ArrayList();
for (var dataLine in dataLines) {
var dataPair = dataLine.Split(commaChar);
buildDataPairs.Add(dataPair);
}
var dataPairs = buildDataPairs.ToArray();
Debug.Log(dataPairs[2][1]); // prints "fish"
Debug.Log(dataPairs[3][0]); // prints "goat"
}
Or, in C#:
using UnityEngine; public class ReadData : MonoBehaviour {
public TextAsset dataFile;
void Start() {
string[] dataLines = dataFile.text.Split('\n');
string[][] dataPairs = new string[dataLines.Length][];
int lineNum = 0;
foreach (string line in dataLines)
{
dataPairs[lineNum++] = line.Split(',');
}
Debug.Log(dataPairs[2][1]); // prints "fish"
Debug.Log(dataPairs[3][0]); // prints "goat"
}
}
Answer by johan-skold · Apr 28, 2010 at 03:29 PM
If I understand this correctly, you basically want a list with string key/value-pairs? For C# - if you're fine with having unique keys - you could use a Dictionary:
using System.Collections.Generic; using UnityEngine;
public class Test : MonoBehaviour { private Dictionary<string, string> pairs = new Dictionary<string, string>();
public void Start()
{
pairs["foo"] = "bar";
pairs["foo2"] = "bar2";
}
}
I do not believe javascript has Generics support however, and I'm not sure how "proper" unity's javascript support is. If it's true javascript you could use built-in arrays. If not, you could settle for a HashTable (untested):
private var pairs : Hashtable = new Hashtable();
function Start() { pairs["foo"] = "bar"; pairs["foo2"] = "bar"; }