Finite State Machines [Part 1]

Finite State Machines might be something that all developers might have heard at least once in their few years starting game development in Unity.

What is a Finite State Machine anyway? Well, there is a lot to cover that is why we’re going to do at least 3 parts. Basically, a Finite State Machine (or FSM) is a design pattern where automation comes in play. Commonly used in AI implementations for certain behaviours. Ie: Walking, Attacking, Idling, etc. FSM can be also implemented in NPCs and is most common in Open World RPGs.

fsm1Let’s treat FSM as an overseer:

Now, the overseer checks the state of an AI. Depending on the state, the AI will react on it. Also, depending on the type of an AI (whether it is a flying type, or ground type, or swimming type) is the action that the AI will make. In this scenario, FSM tells the AI that he is in the “Patrol State”, and will tell the AI to “Walk from A to B”. Unless that there’s a change in state, the AI will only walk from A to B.



To change state, first we must have a condition. In the image on the left, the AI sees the player, and tells the overseer. Now the overseer will change the AI’s state, and will start attacking.



1ZmLLoS1bAl71Ea_BNZzHWaja5YsjvqLa2z-ubNYAgain, the AI starts to patrol again since the player is not in his line of sight.

As seen in these poorly made drawings, every state has their conditions before changing to other states.

Let’s look at the diagram below.





Here is a diagram of states of a normal AI. Red lines represents false on the condition that is required to change in state. The diagram is pretty straight forward. The AI will be on Idle State if it reaches its destination, and vice versa. If he sees an enemy, it will start to attack. The FSM now handles all transitions between states and helps the AI do the action that is available for that state.

Now let’s break down our FSM System.

  • Main FSM System – This is will be the one who will control the AI’s states and checks if the conditions between states. The Main FSM will contain all the states, and will handle the event calls from the FSM Actions.
  • FSM State – This determines the current state of the AI and contains all the actions that is placed on the AI.
  • FSM Action – This will be the action that the AI will do when the AI is in a specific state.

Now how will we do it? Let’s map everything out.


This will be the loop of our FSM. First we initialize the FSM, create states, create actions, and map them all together. After we have mapped them, we will now start the FSM and indicate the state that the AI will start to. Now, the AI will change to a specific state, and the FSM will initialize the action, update it until it the action finishes and sends an event indicating that the action is finished. Finally, the FSM will go back and change the state.

Another thing that will cause a change of state is when an event is called outside the AI’s logic. Like when we create a commander and tells all the soldiers to stop moving.

This ends the first part of our FSM tutorial. I hope that I’ve explained FSM well to you. If you still don’t get it, probably you’ll need to see everything in action first, and see scan everything for yourself. That’s how I learned it.
On the next part, we will first discuss again some simple real life FSM implementations, and we will start scripting our whole FSM Engine from scratch!

[Tutorial] Implementing a Minimap in Unity

What does it take to create a mini-map for a Unity game? You most probably would be surprised to hear that it’s easier than you think, and that it does not even require any programming skills! Here I will try to explain how to make one step by step.

Basic minimap concepts

Minimap known from World of WarcraftMinimaps (or radars) are known for displaying information about our surroundings. First of all, mini-maps should be centered on main character. Secondly, it should use readable symbols instead of real models because minimaps are often quite small and the player wouldn’t recognize the information that the minimap is trying to present.

Most minimaps are circular, so we will also try to create one. Quite often you will find additional buttons and labels attached to it. That’s what we will try to recreate too.

Preparing the scene

Let’s start with adding something to the scene. I’ve created a new scene with Unity Chan (she will be the player) and two robots (as enemies).


Game view

Now let’s add a second camera. Just click on GameObject -> Camera and rename it to Minimap Camera. Then make this camera a child of Unity Chan model (so it will follow her) and move it 10 units above her head looking down.

Minimap Camera Setup

Minimap Camera Setup

For good effect set Transform position to 0, 10, 0 and rotation to 90, 0, 0. The camera should be seeing something like this:

minimap camera preview

OK, but that’s not a minimap yet. When you will launch your scene now, the picture from the camera above will be the only one rendered on the screen. We have to tell the game that we want the minimap to be a Unity UI element.

Rendering to Unity UI

To do that we will require a Render Texture. You can easily create one by choosing Assets -> Create -> Render Texture from the main menu. Create and rename it to Minimap Render Texture.

minimap render texture

Now select Minimap Camera and in the Inspector assign Minimap Render Texture to Target Texture field.

camera assign render texture minimap

If you will try to launch the scene you will notice that Minimap Camera picture is nowhere to be seen. The result image is now hidden in our newly created render texture.

Let’s now create a Canvas to add UI elements on it. Choose GameObject -> UI -> Canvas and you will be able to find one on your scene.

created canvas

Canvas would require a Raw Image to use Render Texture on it. Select GameObject -> UI -> Raw Image, rename it to Minimap Image and in its inspector assign Minimap Render Texture into a Texture field.

raw image render texture

It will result with a Unity UI element that now renders Minimap Camera image in it!

raw minimap unity ui

Now let’s make it round. For this purpose I made a simple mask texture:

minimap masl

Create a new Unity UI image, add Mask component to it, set our new mask texture to Source Image inspector field, and make Minimap Image a child of our Mask. (Tip: disable Mipmaps for mask textures to get a better visual effect).

minimap mask configuration

This setup will make our minimap look like this:

minimap masked circle

White minimap on white background will not look so good. Let’s add a border image over it:

minimap border

minimap with border

To make moving it around simpler, I’ve grouped everything under empty game object called Minimap.

minimap game object

Finally let’s move our new minimap to top-right corner of the screen.

minimap top-right corner

Looks nice, doesn’t it? But it is still not a valid minimap just, it’s a camera rendering game from the top. If you’re familiar with layers then most probably you know what I will do next!

Fun with layers

We will need at least one additional layer. Go to Edit -> Project Settings -> Tags and Layers and add a new layer caller Minimap.

layers minimap

Now lets create three spheres. One will be blue and should be located in the same place where Unity Chan is standing. The best would be to make this object a child of Unity Chan. Finally make sure to set its Layer to Minimap.

unity chan blue sphere

Do the similar for two Robots, but instead of blue sphere make them red!

robot red spheres

Now is the best part! Select the Main Camera and make sure than its Culling Mask has Minimap layer unset.


Then select the Minimap Camera and do the opposite. Leave only Minimap set and disable all the rest.

minimap camera layers

Now you can see something that looks quite like a valid minimap!


Final touches

You may want to make few adjustments. First of all, let’s change Minimap Camera clear color to light-gray and Clear Flags to Solid Color, so the minimap background will do a better contrast with red and blue spheres.

minimap camera background color

Then you can add any other Unity UI element to stick with your minimap. I will add an example label. And here’s our final result!

minimap final result

Minimap is configured in a way that moving the character will update its position. If any other robot will move too, it will be immediately visible.

minimap position change

And this concludes the Unity mini-map tutorial! Feel free to ask any questions you may have in comments. Don’t forget to subscribe to our newsletter for the latest Unity tips & tricks.

How to Use Unity’s Resources Folder

Unity has several kinds of special folders. One of them is the Resources folder. Simple concept of storing assets is well-explained in the official documentation:

Generally, you create instances of assets in a scene to use them in gameplay but Unity also lets you load assets on demand from a script. You do this by placing the assets in a folder called Resources or a sub-folder (you can actually have any number of Resources folders and place them anywhere in the project). These assets can then be loaded using the Resources.Load function.

Still the reason why we might want to use the Resources folder may be a little confusing. First you have to understand how Unity build process is works and how Unity is able to access game assets.

Unity build process

Before you will build your game, you have to declare what scenes your game consists of. All of this can be done in Build Settings window.

build settings window

There are at least two reasons why Unity asks you to do this:

  • It needs to know what scene should be loaded first (the top scene)
  • It needs to know what assets should be included in your build (dependencies)

What are scene dependencies? They’re assets which are connected to the scene hierarchy in any way, usually as a component field.

Unity Logo object contains Sprite Renderer object that references Unity Logo asset.

Unity Logo object contains Sprite Renderer object that references Unity Logo asset.

The dependency diagram may look like this:

dependency diagram 1

In this case there are two scenes. Scene 1 is using Asset 1 and Asset 2. Scene 2 is using Asset 2 and Asset 3. What happens if you decide not to build Scene 2?

dependency diagram 2

Only Asset 1 and Asset 2 will be included in the build since Asset 3 is referenced only by Scene 2, that is no longer included in the build. Thanks to this dependency tracking Unity will include in your build only these assets, which are actually used. Needless to say that you don’t have to worry about storing assets you’re not using at the moment. It will not affect your build size in any way.


There’s a way to get around this process. If you put your assets into a Resources folder, they will be always included in your build. But be careful! You need a really good reason to do so!

As I said before, in most cases when you need to use an asset, you make a reference to it within a scene. It’s really easy to use any kind of attached asset this way. So why would you need to use an asset without keeping a reference to it? There may be several reasons and each one depends on specific needs of the, but let’s look at one case what is quite common for most games.

When an asset is directly referenced from the scene, it will be loaded into the memory before your scene will be launched. Thankfully to that, player will not experience any frame-drops related to assets loading (with small exceptions). The price is of course the time needed for these assets to be loaded. Sometimes it may be not acceptable.

Example – loading screen with different backgrounds

Many game loading screens are displaying random images to be less boring.

Many game loading screens are displaying random images to be less boring.

Loading screen is something that usually is also a scene. Let’s think of a case when you want to display a random image on the background while your actual game level is loading. You’ve collected 15 images and you add these to loading scene images rotation script. It is working great, but when you play your game you realize that your loading scene requires more time to load than you need to pass your actual game levels!

This is caused by assets pre-loading mechanism and can be easily fixed using Resources folder. First remove all the references to your textures from the scene. Then put your images into Resources/LoadingImages directory like this:

resources images

Then somewhere in the code you can use a code like this one:

Note that Random.Range() returns a random number between first argument inclusive and second argument exclusive, that’s why there’s +1.

If you will need to attach this texture to an Image component, you can do it like this:

A word of caution

Use Resources folder only when you really need to. Loading assets on demand will make your FPS rate drop, and having indirect dependencies is makes your work much more difficult.  It’s worth to mention again that these assets will always be included in your build, even if you don’t use them. You have been warned!

How to Use Multiple Cameras in Unity3D

Understanding the Importance of Using Multiple Cameras in Unity

From what I observe, many Unity users do not grasp the concept of using multiple Unity cameras on a single scene. “If I want to look from only one perspective, why do I need more than one camera?”. Saying that it makes perfect sense when more than one camera captures the scene from the same perspective makes it even more confusing. So why even bother? The reason is somewhat complex, but it’s really worth learning. It will help you create great visual effects, that are hard to accomplish with the use of only one camera, in an easy way.

What is the Unity camera?

Before we can continue, you have to understand what Unity Camera actually is. When Unity renders the scene it needs much of important information to be set up, but let’s simplify that list to make it easier to understand. Let’s consider:

  • List of objects to render
  • Camera’s perspective (position, rotation, scale, field of view, clipping etc.)

If you’re already experienced in that matter you might’ve noticed that I’m not speaking about matrices. Let’s just ignore math-related stuff for now.

List of objects to render is a list of all objects on the scene, right? Wrong! Each camera renders only the objects visible to it (field of view, frustum culling) and those on the layer which actually seen by the camera (Culling Mask.)

camera culling mask

Culling Mask can be set to Everything, or you may set which of the layers should be seen. This is one thing what layers are for.

This camera sees everything.

This camera sees only the Default layer (ground) and the Red layer (red sphere).

This camera sees only the Default layer (ground) and the Red layer (red sphere).

The conclusion is that different cameras can render different objects. This is important information even if you don’t know yet how to use it in practice. It also means that adding second camera will not re-draw your scene two times. Only objects visible to the second camera will be rendered. Knowing this having multiple cameras rendering different layers will result in similar efficiency as rendering all these layers using only one camera.

Let’s then answer the main question: Camera is an instruction to render specific list of objects from given perspective.

What do cameras render?

Wait, haven’t we just answered that question?! Well… not exactly. There’s a visible and an invisible part. What you can see is a result image (let’s call it color buffer). And of course there’s a thing that you cannot see. This thing is called a depth buffer (called also z-buffer).

Depth buffer can be easily described as a game screen sized gray-scale image, every pixel of which represents how close that pixel is to the camera (to be honest this is not 100% true but let’s not think of more complicated cases now.) It is used by the GPU to decide whether to-be-rendered pixel should be processed or rejected from rendering. As a result, pixels that are obstructed by other pixels are not going to be visible (just like in the real world.)

depth buffer

Camera order and clearing

Before rendering anything into color buffer and depth buffer, camera can clear both buffers or only the depth buffer. Did you notice that the default Unity 5 scene camera clears buffers to Skybox?

clear flags skybox

There are some more options there:


  • Skybox replaces color buffer with your skybox and completely clear depth buffer
  • Solid color does the same, but color buffer becomes solid color
  • Depth only leaves color buffer at is, but your depth buffer becomes clear
  • Don’t Clear doesn’t clear anything.

What will happen if we will try to set the default camera Clear Flags to Don’t Clear? Well, the effect may be interesting (I moved the camera a little after entering the Play mode).

camera don't clear

It looks like our sphere duplicated itself so many times, that it turned into some kind of wired, rounded pipes thing. Besides that there’s still one red sphere on the scene (note that Blue layer is still not visible to the camera), the game scene image looks valid. There are no graphical artifacts of any kind. Yet we managed to create an effect of many duplicated objects with only one object.

This happened because color buffer was not cleared between frames (colors rendered previously were transferred to the next frame), also the depth buffer. Depth buffer remembered that something has been rendered and it was keeping this information when Unity tried to render another frame. When sphere was about to be rendered behind already rendered sphere image, invisible pixels were discarded. The same thing applies when there are many objects on the scene rendering one after another.

If you still don’t understand what just happened, please stop reading now and try doing it yourself! Make a new scene, add an object, set camera Clear Flags to Don’t Clear and move either your object or your camera.

What is it good for?

I assume that you don’t want this kind of effect in your game, so what’s the clearing good for? Let’s now try to create two cameras.

  • Blue Camera
    • Clear Flags: Skybox
    • Culling Mask: Default, Blue
    • Depth: 0
What Blue Camera sees.

What Blue Camera sees.

  • Red Camera
    • Clear Flags: Don’t Clear
    • Culling Mask: Red
    • Depth: 1
What Red Camera sees.

What Red Camera sees.

There’s one new parameter: Depth. Depth defines the order of rendering of the cameras. Camera with lower depth will be rendered before the camera with a higher depth.

Let’s see how Unity will render this scene step by step (again not 100% accurate, but it’s only to understand the process):

  • (Blue Camera context)
  • Color buffer is cleared to Skybox
  • Depth buffer is cleared
  • Plane (Default layer) and blue sphere (Blue layer) are rendered
  • (Rex Camera context)
  • Nothing is cleared
  • Red sphere (Red layer) is rendered

As the result you get a scene that looks exactly like rendered using a single camera:


So why bother? Let’s try one thing. Let’s switch Red Camera Clear Flags from Don’t Clear to Depth only:

depth only clear

Whoa, do you see that? Since depth buffer has been cleared, the red sphere doesn’t know that its pixels are obstructed, so it’s rendering like there’s nothing on the scene. That means that clearing the depth buffer brings rendered objects to the front. This may be super-useful when you’d like to render 3D UI elements.

In Skyrim you can see inventory items as 3D objects. These are rendered correctly even if background object appears closer to the camera.

In Skyrim you can see inventory items as 3D objects. These are rendered correctly even if background object appears closer to the camera.

Another interesting option is applying camera effects only to specific layers. Let’s try to apply blur to the Blue Camera, just like on the screenshot below:

camera blur effect

Let’s now switch  Red Camera Clear Flags back to Don’t Clear and apply a different effect to the Blue Camera: Grayscale.


Finally, keep in mind that if you want to move the camera, you may want to move all cameras at once (that’s why keeping all the cameras as a child of one game object is quite common.) But moving only one camera may be somewhat desired…

moving two cameras

How to create 2D infinite runner in Unity

[Tutorial] – Create a Procedurally Generated Terrain for a 2D Infinite Runner Game in Unity

Have you ever been thinking of creating infinite runner game with the Unity? This kind of games can be quite challenging even for experienced developers. One of the things you most probably want to have in your game, is a procedurally generated terrain. Here we will show you how to achieve such feature using the Unity game engine.

Tiny Wings for iOS

Tiny Wings for iOS

The theory

We will write a script that will split the level to segments. Each segment is a constant size object including a Mesh. When the camera is about to render a segment, the Mesh is generated and set on the target position. Segment that is no longer visible is released back into the pool.

Sounds simple? Then let’s get started…

Set up

First, we will need a prefab with Mesh Filter and Mesh Renderer. We will use these to render segments.

Mesh Renderer and Mesh Filter prefab.

Mesh Renderer and Mesh Filter prefab.

Now let’s start writing our script. Let’s call it MeshGen.

Next, when the script is awaken, we want to initialize its fields and build the mesh pool. We’re using a pool to minimize the garbage collection.

One thing that definitely needs an explanation is a triangle order thing. You can see that it is kind of messed up. For unity meshes you need to define triangle indices. These indices are the indices of vertices passed just before. Each triangle has three vertices. There are two ways you can pass these vertices – clockwise or counter-clockwise. Since most Unity built-in shaders (and any shaders) are rendering counter-clockwise ordered triangles, and discarding (culling) clockwise ordered triangles, we have to follow the rule.


Here’s an example of 4-vertices shape. It can be displayed using two triangles. If vertices are defined as above (0, 1, 2, 3 in order), then the triangles should be defined as follows:

  • 0-2-1 (alternatives: 2-1-0 or 1-2-0)
  • 3-1-2 (alternatives: 1-2-3 or 2-3-1)

Height function

What we will need is a height function. This should be a Pure Function and can be modified freely to get different interesting results. For our case we made a combination of two sine functions.

Generating segment function

When we have the height function, we need a function that will generate a mesh based on the returned value.

We’re computing as many vertices as defined by SegmentResolution field value. Also, we’re using _vertexArray,  because it is already allocated and it is not used by any other object (assigning the array to the mesh will copy it instead of passing the reference, but this does not generate any garbage). Vertex positions are relative, but the position passed to GetHeight() must be absolute.

Checking if segment is seeable by the camera

You have to check if segment is about to be rendered by the camera. This is done using this method:

Storing data about visible segments

If a segment will be displayed, we have to store this information in some way. We will need segment index and also we need to know what MeshFilter has been used to draw that segment. Then, we can put it back into the pool when the segment is no longer visible. We will create a helper struct within MeshGen class:

Then, within the MeshGen class there will be one more private field:

We’re using struct instead of class because creating new struct does not generate any garbage.

Checking if segment is currently visible

We will need to check if a segment is currently visible, so we don’t use more than one MeshFilters to render the single segment.

The name of SegmentCurrentlyVisibleListIndex can be a little confusing. It’s looking for a segment of given index, and if found, it returns an index of this segment within _usedSegments list.

Making the segment visible

Now, it’s the most important part, making the segment visible! To do this, we created the EnsureSegmentVisible() method. It takes segment index and makes sure that given segment index will be visible after executing this method. If this segment is already visible, it does nothing.

Hiding the segment

When the segment is no longer visible by the camera, it should be removed and the MeshFilter should be given back to the pool. We did that with  EnsureSegmentNotVisible() method. It is opposite of the previous method.

Connecting it all

Now, the sweet part. The update function! It should hide all the segments that are no longer visible and display segments that should be visible. The order is important here, because otherwise we can run out of free MeshFilters.

Procedurally generated terrain result

It is working? Let’s move the camera position and check it out.

generated terrain gif

The package

Here you can download the unitypackage suitable for Unity 5.3.1 and above. Feel free to modify it to your needs! If you have any questions, please add those as a comment to this post. We will be more than happy to help you!