Today Tobi could try out our level editor for the first time. Of course there are still some issues to smooth out and it still looks rather boring because Annick hasn’t startet with the graphics yet but at least the most important features are working. So, how does it work?
Reading the map from a .txt file
Most of the action happens in the ImportText class:
using UnityEngine; using System.Collections; using System.Text.RegularExpressions; public class ImportText : MonoBehaviour { public TextAsset textFile; //function to read the Level file public string[][] readFile(int level){ TextAsset bindata= Resources.Load("level"+level.ToString()) as TextAsset; string textRead = bindata.text; string[] lines = Regex.Split(textRead, "\n"); int rows = lines.Length; string[][] levelBase = new string[rows][]; for (int i = 0; i < lines.Length; i++) { string[] stringsOfLine = Regex.Split(lines[i], " "); levelBase[i] = stringsOfLine; } return levelBase; } }
This function reads the text file that corresponds to the current level. Those files all look something like this:
W W W W W W W W
S 0 0 0 0 1 0 W
W 1 1 b 1 1 0 W
W 1 1 c 0 0 0 Z
W c 0 0 0 1 0 W
W W w W W W W W
Each different letter corresponds to a different prefab with different scripts and components attached. Another class takes the two-dimensional array created in ImportText and instantiates the corresponding objects in a grid.
Implementing the game logic
For the game logic – especially movement and collision detection – I took a lot of ideas from the official Unity 2D Roguelike tutorial. I’m working with a GameManager, that uses the Singleton pattern and keeps track of collected items and the level number even if a new scene is loaded. While I knew about Singletons from university I found the line
DontDestroyOnLoad (gameObject);
really useful. I wish I had found out about this when I was doing my first Unity project two years ago.
Also the tutorial’s way of implementing movement, item pick up and collision was really helpful. While I haven’t added enemies yet, I could modify the code to get the walls moving on their own and instead of attacking enemies I could implement the walls that can be destroyed with bombs.
And now?
If I realized anything during the last days of finishing the editor is that there is so much more to learn about Unity and game developing in general. I’m really excited to smooth out the last problems and to implement some additional features like doors and keys, enemies or NPCs. Also I’m really looking forward to Annicks graphics since my placeholder sprites aren’t that exciting.