Unity 2D Platformer – Level Generator

programming level generator - 2d platformer

For some time now I have been experimenting here and there with the 2D and 3D engine Unity. Especially the programming of a 2D-Platformers has been very interesting for me.

However, programming a 2D game (if you are a programmer) is not the biggest problem, but in my opinion the look, because I am not a graphic designer. 😀

Table of contents:

Creating Unity 2D Platformer and Level Generator

AmazonSo you can't avoid building some tools like a texture generator in Python Python or a small level generator in CSharp as described in this article.

Who has already created his Prefabs in Unity and now has the empty scene in front of him knows how difficult it can be to design a level and to place everything correctly in the scene.

Layers, floors, walls, respawn points for the player, enemies, items you can collect to get points, and much more.

So how can you speed up the creation of a level and place all game objects correctly?!

The idea is simple and easy to implement in an extremely short time. For each level you create an image or an initially transparent PNG file in Photoshop or GIMP and color the pixels you want to create a GameObject on.

First of all, the color values for the prefabs are defined. Example: The pixel for the starting point of the player becomes green (RGBA: #00ff00ff). Floors are marked blue (RGBA: #0000ffff), opponents / enemy red (RGBA: #ff0000ff) and items to collect get a yellow pixel (RGBA: #ffff00ff).

You can extend the list as you like, depending on how many different objects you have. To avoid using too many colors, you can for example group items very well by setting all items/collectables to yellow as usual, but when loading later always randomly loading another collectable item to the position in the level. Only one approach of many...

Such a level PNG file (GIMP screenshot - width 32px, height 8px) then looks like this:

2D Platformer - Level GeneratorSo you save the graphic in PNG format and drag it in your 2d Platformer project in Unity into the assets directory.

Unity 2D Platformer - Level GeneratorThe level graphics should later all be under "Assets/Resources/Level/Level1.png".

(Level1.png, Level2.png, and so on...)

IMPORTANT: In order for the whole thing to work as it should, you must first set the texture settings for each level PNG.

+ Filter Mode: Point (no filter)
+ Compression: None!
+ Read/Write Enabled: true

Then click on Apply at the bottom right. So far so good.

Programming - Unity 2D Platformer - Level Generator

Now we just have to write some code so that our game knows what to do with these great pictures. First you create a new C# script and call the class LevelGenerator. In the LevelGenerator.cs you first insert a structure which can store the necessary information (prefab and color) for each object and create an ArrayList in which you can put every single object.

private struct pixObject{
public Color pixColor;
public GameObject prefab;
}
private ArrayList pixToObject = new ArrayList();

Next, we need a function to write the prefabs and color values into the ArrayList, so that we can later create the clones of the objects using Instantiate. I named the function initPrefabs:

public void initPrefabs(){
if (pixToObject.Count > 0) //skip if already initialized
return;

pixToObject = new ArrayList();

pixObject o = new pixObject();
o.pixColor = Color.blue; //ground blue
o.prefab = Resources.Load<GameObject>("Prefabs/GROUND_1x1"); //Fullpath: Assets/Resources/Prefabs/GROUND_1x1.prefab
pixToObject.Add(o);

o = new pixObject();
o.pixColor = Color.green; //Player green
o.prefab = Resources.Load<GameObject>("Prefabs/Player");
pixToObject.Add(o);

o = new pixObject();
o.pixColor = Color.red; //Enemy red
o.prefab = Resources.Load<GameObject>("Prefabs/Enemy");
pixToObject.Add(o);

o = new pixObject();
o.pixColor = new Color(1, 1, 0, 1); //Item/Collect yellow
o.prefab = Resources.Load<GameObject>("Prefabs/Collect");
pixToObject.Add(o);
}

In this function you fill your ArrayList. The code should be self-explanatory. You create a pixObject, set the desired color, give it the appropriate prefab and write the object into the ArrayList.

In the next step you create a function addObject which includes a desired pixel (xy coordinate) from the level PNG, and depending on the color, sets the appropriate object to the location in the game.

private void addObject(int x, int y, ref Texture2D tex){
Color pixColor = tex.GetPixel(x, y);
if (pixColor.a == 0) //ignore transparent pixels
return;

foreach (pixObject o in pixToObject){
if (o.pixColor.Equals(pixColor)){
Vector2 pos = new Vector2(x, y);
Instantiate(o.prefab, pos, Quaternion.identity);
}
}
}

Now I have written a function called loadLevel, which takes the number of the desired level as parameter. At this point, the path to the desired level PNG is formed. The content of the file is read into a byte array and then loaded via LoadImage into a Texture2D object, which makes it very easy to read the pixels as seen above.

Now that the Texture2D object mapTex is ready to start, the individual pixels in the image are passed through in a For-Loop and addObject (see above) is called to evaluate the respective pixel.

UPDATE: On mobile devices with Android or iOS loading via ReadAllBytes fails because the relative path was not correct. If you load the level PNG image directly via the Unity engine via Resources.Load as Texture2D everything works as desired and the platform independent. The code was adapted accordingly.

public bool loadLevel(int levelNum){
string sFile = "Level/Level" + levelNum.ToString();
Texture2D mapTex = Resources.Load(sFile) as Texture2D;

for (int x = 0; x < mapTex.width; x++){
for (int y = 0; y < mapTex.height; y++){
addObject(x, y, ref mapTex);
}}
return true;
}

That's almost it. Don't forget to call the two functions (initPrefabs and loadLevel) at load. Put it in your void Start() as seen below.

private void Start(){
initPrefabs();
loadLevel(GameControl.control.currentLevel);
}

You can then insert the LevelGenerator as a component into an empty GameObject in your scene. Done! The result looks like this:

Unity 2d platformer - ingameAmazonThe code can be downloaded here: LevelGenerator.cs

I hope the approach, the code and the explanations are reasonably understandable.

Questions, praise, criticism and other feedback are welcome. Just leave a comment.

Author: Sascha from Tinkering-Sascha.com

Author: Sascha

Some words about myself. My name is Sascha - i'm in my mid-30s and a software developer and martial artist from germany. Besides programming and martial arts some of my interests and hobbies are cooking, fitness and hearing loud heavy metal music. :D

Related postings

Program your own Screen Recorder / Capture Software

While searching for an easy to use screen recorder tool, I stumbled across all kinds of free and paid software solutions. From my point of view, pretty much all of them were either completely overloaded, difficult or complicated to use. Others were just expensive in relation to the functionality. My conclusion: Program yourself! Table of … Continue reading “Program your own Screen Recorder / Capture Software”


Flashing firmware – ESP8266-WiFi-Module

Since I recently started to deal more intensively with the topics “Smart Home” and “Home automation” I decided to publish some of my construction sites, stumbling blocks and solutions here. As already mentioned in the article about my Smart-Home-Project V1 I use the WLAN module , because it is small, reliable and cheap. In this … Continue reading “Flashing firmware – ESP8266-WiFi-Module”


WordPress Plugin: Statistics-Light

Statistics-Light – A lightweight statistic tool for WordPress Before the DSGVO (General Data Protection Regulation GDPR) it was almost standard to integrate “Google Analytics” and other tracking services and software on your own website, blog and shop. The disadvantage was (and still is) that the data was transferred to the USA and evaluated there by … Continue reading “WordPress Plugin: Statistics-Light”


My ShoppingList App / Grocery List App

Here are some informations, Screenshots and Download-Links for the Shopping List App (Pro-Version) for iOS- and Android-Devices. Table of contents:My ShoppingList App / Grocery List AppShopping List App – Description iOS (iPhone, iPad)Shopping List App – Description AndroidShopping-/Grocery-List App – Free-Version My ShoppingList App / Grocery List App   Some cool new feature is, that … Continue reading “My ShoppingList App / Grocery List App”


My Recipes Book – Cooking Recipe Manager

Here are some informations, Screenshots and Download-Links for the Recipes Book App (Cookbook) for iOS- and Android-Devices. My Recipes – Create your own wonderful recipe collection on your and . Table of contents:Recipes Book – Cooking Recipe ManagerMy Recipes Book App – Description iOS (iPhone, iPad)Cooking – Recipes Book App for iOS – VideoMy Recipes … Continue reading “My Recipes Book – Cooking Recipe Manager”


Leave a Reply

Your email address will not be published. Required fields are marked *

I have read and accepted the privacy policy!