Here is the overall solution for creating an level based on an TXT file:
Textfile looks like this:
S 0 0 0 1
0 0 1 0 2
2 0 0 2 1
We need to read the file and save it’s content into an twodimensional array. We will split by line breaks and spaces:
string[][] readFile(string file){
string text = System.IO.File.ReadAllText(file);
string[] lines = Regex.Split(text, "
");
int rows = lines.Length;
string[][] levelBase = new string[rows][];
for (int i = 0; i < lines.Length; i++) {
string[] stringsOfLine = Regex.Split(lines*, " ");*
_ levelBase = stringsOfLine;_
* }*
* return levelBase;*
* }*
In the next step we are going to iterate through the matrix and instantiate the Prefabs we bound to our Script via public variables:
* public Transform player;*
* public Transform floor_valid;
public Transform floor_obstacle;
public Transform floor_checkpoint;*
* public const string sfloor_valid = “0”;
public const string sfloor_obstacle = “1”;
public const string sfloor_checkpoint = “2”;
_ public const string sstart = “S”;*_
* void Start() {*
* string[][] jagged = readFile(“D:/level1.txt”);*
* // create planes based on matrix*
* for (int y = 0; y < jagged.Length; y++) {*
* for (int x = 0; x < jagged[0].Length; x++) {*
* switch (jagged[y][x]){*
* case sstart:*
* Instantiate(floor_valid, new Vector3(x, 0, -y), Quaternion.identity);
_ Instantiate(player, new Vector3(0, 0.5f, 0), Quaternion.identity);_
_ break;_
case sfloor_valid:
Instantiate(floor_valid, new Vector3(x, 0, -y), Quaternion.identity);
_ break;_
case sfloor_obstacle:
Instantiate(floor_obstacle, new Vector3(x, 0, -y), Quaternion.identity);
_ break;_
case sfloor_checkpoint:
Instantiate(floor_checkpoint, new Vector3(x, 0, -y), Quaternion.identity);
_ }_
_ }_
_ } _
_ }_
Here is the result of this. I was reading a 10x10 matrix holding several different strings (just like the mentioned text file):
_![alt text][1]_
I hope this will help all you guys for making games with nearly no effort to create new levels. I would also like to thank [gajdot][2] who helped me a lot in finding the answer.
_[1]: http://answers.unity3d.com/storage/attachments/18104-unbenannt.png*_
_*[2]: http://answers.unity3d.com/users/246911/gajdot.html*_