My first Unity game
A few weeks ago, I started a course in game development with Unity3D. So far, it’s been a lot of fun to do something completely different to my day-to-day work. I finished my first project, which is a Arkanoid/Breakout clone. It only has four levels, but that’s fine, I guess. Although I built it by following the course, I went outside the curriculum for the level building. In the course, you create the levels completely by hand. You place each block where you want it, which is quite a lot of work.
As a developer, I want to do tedious stuff like that through code, not manually. So, I created some code that positions the blocks based on a two dimensional array. This allows me to quickly create some layouts. Of course, it’s limited to straight rows, so it is a bit more limited than manual crafting. But for my purposes it’s perfectly fine.
This is the code that loads the layout array and processes it.
using UnityEngine; using System.Collections;</code> public class BrickBuilder : MonoBehaviour { void Awake () { int[,] layout = LevelLayout.GetLevelLayout(Application.loadedLevelName); Object prefab; for (int y = 0; y < layout.GetLength(0); y++) { for (int x = 0; x < layout.GetLength(1); x++) { Vector3 position = new Vector3(x +.5f, (y * 0.32f) + 9f, 0); if (layout[y, x] == 9) { prefab = Resources.Load("Unbreakable"); } else { prefab = Resources.Load(layout[y, x] + " hit"); } if (prefab != null) { Instantiate(prefab, position, Quaternion.identity); } } } } }
And this is the code that returns the layout array, plus an example array.
using UnityEngine; using System.Collections; using System.Collections.Generic; public class LevelLayout : MonoBehaviour { static private Dictionary<string, int[,]> layouts = new Dictionary<string, int[,]>(); void Awake() { layouts.Clear (); int[,] level01 = new int[,] { { 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0 }, { 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1 }, { 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0 }, { 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1 }, { 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0 }, }; layouts.Add ("Level_01", level01); } static public int[,] GetLevelLayout(string loadedLevelName) { if (layouts.ContainsKey(loadedLevelName)) { return layouts[loadedLevelName]; } else { return null; } } }
Use the links below to download it.