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 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

self-construction - DynDNS-Alternative

If you already have your own webserver/webspace on the Internet and some programming knowledge, you can save yourself a service like DynDNS.org & Co. without much effort if you want to access parts of your home network from the road. Such services provide a host name/URL (e.g. my-home-network.dyndns.org) which is then forwarded to the IP … Continue reading "self-construction - DynDNS-Alternative"


pi_robot - Playing with Raspberry Pi, iPad and some Code

The Raspberry Pi is still one of the most popular mini computers, not only among hobbyists. Cost-effective (about 30 to 40,- EUR depending on the model), flexible in the field of application and at the latest since the equipped with enough CPU power and memory to solve even more complex tasks. With the 1.2 GHz … Continue reading "pi_robot - Playing with Raspberry Pi, iPad and some Code"


Telegram Messenger and the Bot API - Part 2

In the first part - Telegram Messenger and the Bot API - I explained some basics how to set up a telegram bot and how to use it to send messages, states, informations and more to your . Since this tool has proven to be very practical, I decided to take up the previous article … Continue reading "Telegram Messenger and the Bot API - Part 2"


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"


Smart Home V1 - Do it yourself

I've been planning my smart home for some time now. Besides the cost factor for all the great things I imagine, I often lack the necessary time for detailed planning and implementation. So I decided to start somewhere and write down this DIY project in parallel...let's see where it leads...I ask for your indulgence if … Continue reading "Smart Home V1 - Do it yourself"


Leave a Reply

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

I have read and accepted the privacy policy!