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

kraken.jpgSo 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

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

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

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

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

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

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(){

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 - ingamekraken.jpgThe 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 a software developer, trader and martial artist from germany. Besides programming, trading and martial arts some of my interests and hobbies are cooking, fitness and hearing loud heavy metal music. :D

This might also be interesting for you

Telegram Messenger and the Bot API

Telegram is basically a messenger similar to Whatsapp or Threema , free and easy to use. I don't want to say that it is better or worse than other messengers, but I like the Telegram Bot API so much that I want to write a little tutorial here. Table of contents:Using Telegram Messenger and the … Continue reading "Telegram Messenger and the Bot API"

Privacy Browser for more security and privacy

More data protection, security and above all more privacy on the Internet is demanded from all sides, and not only after the entry into force of the EU-wide data protection basic regulation (). In general one can understand this wish, because who would like to voluntarily allow large IT companies to pass on their own … Continue reading "Privacy Browser for more security and privacy"

Programming: PHP image captcha code

Here I would like to present my small but nice capture code solution, which I programmed some time ago. I was tired, also with regard to the german DSGVO (privacy laws), to include capture solutions of external providers. In addition, various privacy browsers block e.g. also javascripts, so that an external image capture module for … Continue reading "Programming: PHP image captcha code"

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"

Leave a Reply

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

I have read and accepted the privacy policy!