Programming With Unity Tutorial – Unityscript / Javascript – 02 Variables

Mel_Georgiouin the last tutorial, we had a good look around the Unity UI, got a basic understanding of how to attach scripts to GameObjects, and how to use the console to display messages and debug our projects. A pretty solid foundation! Now, its time to learn about variables! =)

Before We Begin…

It would be a good idea to save the project we were just working on (if you already haven’t done so!). Go to File > Save Scene to save the current scene (aka level, frame, etc.). I named the previous lesson “Chapter1 – Hello Console“. Feel free to mimic the file structure I have setup in the screenshot below:


NOTE: You will also notice that I have swapped the location of the Project and Hierarchy panes. This is personal preference, but I prefer this layout! 🙂

… So, What Are Variables?

In the most simplistic terms, variables are ‘things that can change’. In programming, variables can be anything from a number, text, colour, or some other custom type of data.

Another very important aspect, (specifically in Unity) is that variables can be used to make a script far more versatile!

Putting It Into Practice

Let’s look back at our “HelloConsole.js” script from the previous tutorial…

#pragma strict

function Start () {

print(“Hello Console!”);


If you remember, this simple script sends a message to the console with the text “Hello Console!” (in programming terms, “Text” is called a “String”).

What we’ll do in this lesson is show how adding a single variable can make this simple script a whole lot more flexible! First let’s save a new scene and call it “Chapter 2 – Hello Variable

Let’s make a new javascript file and call it “HelloVariable”. Your project should now look like this:


Now we can open the “HelloVariable.js” script, and enter the following code:

#pragma strict

var printText : String = “Hello Console!”;

function Start () {



What’s going on???

Okay, so the script is quite similar to the previous “HelloWorld.js” script, but now we are using a variable to display the message (I’ll show you why this is cool after I’ve explained the code!)

This is the new line that creates the variable:

var printText : String = “Hello Console!”;

What we’re doing here is setting up a variable called “printText“.  All variables in Unityscript have to start with the word var to let the system know that what we are doing is in fact setting up a new variable. The second part is the name of the variable, followed by a “:”, which means we are about to tell the compiler what kind of variable this is. As we are storing text, we want to use a “String” type.

We could put the semicolon (;) there to close the statement if we want, but we’ve also added a value for this variable ( “Hello Console!” ).

So the setup for this kind of statement is like this:

var <name of variable> : <type of variable>;

OR, if you want to add a value to the variable when you set it up:

var <name of variable> : <type of variable> = <value>;

It’s important to note that this particular variable has been created OUTSIDE of any function. This means it will be available in the Unity inspector pane. You’ll soon see why this is super cool!

The next change in this script is in the print() function, where we add the variable instead of a predetermined piece of text (remember, they’re called Strings!).


What we’re doing here is using the value of the  printText variable to be sent to the console. It is acting kind of like a “placeholder” for anything we’ve set the variable to.

Back To The Editor

Just like in the previous tutorial, we’re going to create an empty GameObject in the scene and drag the new “HelloVariable.js” script onto it. This is what things should look like now:


Hopefully you’ve noticed something really cool!

In the inspector, you should now have access to the printText variable we just setup in the script! You’ll also notice that it’s default value is “Hello Console!”

If we run the game now, you’ll see the same result as the previous tutorial:

Unity Hello Console!


Now, let’s go ahead and change the variable in the inspector to “Hello Variable!”.


If we run the game again, we’ll see a new message in the console:



and just like before, we can debug the script easily by double clicking “Hello Variable!” in the console, which will open up the correct line in the scripting editor:



We’ve only just touched on the basics of Variables (in theory anyway), but what we have learned is HOW to create them, and HOW to put them to good use!

We expanded our old script with a single variable which instantly made it a lot more flexible! For example, rather than creating 10 different variations of the same script with 10 different console messages, now we have 1 script which we can use to create  infinite variations (via the editor)!

Variables are a complicated subject, and in the next chapter we’ll be building up our knowledge of them even further!

I hope you guys found this helpful, and I’ll be working on the next tutorial as soon as possible! =)

All the best,

– Mel

Programming With Unity Tutorial – Unityscript / Javascript – 01 Introduction

Mel_GeorgiouSo, you’ve decided you want to learn how to program in Unity, that’s awesome. In this introductory tutorial, we’re going to create a new project in Unity, take a quick look around the main parts of the UI, write a very quick script in UnityScript (a kind of javascript – like language), and get an idea of the workflow involved by building something very basic that will act as the core to all your future projects.

Setting Up A New Project In Unity

After loading the Application, create a new project in Unity by going to the menu and selecting File > New Project. You’ll get a window that looks like this:

Unity New Project Window

Call your project anything you like, in the example above, I named it “My First Project”. You don’t need to import any packages. Click “Create Project” and you’ll be taken to Unity’s main interface screen.

Setting Up The Unity UI

Unity’s interface can get quite complicated when you have loaded up all the tabs and windows, etc. Usually, by default you’ll get a simplified interface looking a little like this:

Unity UI

You can see that the UI is split up with a window for the game / scene view, a hierarchy pane, a project pane, and the inspector pane.

Before I explain what all of these do, let’s add one more element to the UI, the “console”. we can do this by going to the menu and selecting Window > Console. The console will popup in a little window, but if you click and drag the tab of that window (where it actually says “Console”), you can drag it into the UI and dock it inside a part of the main interface. You can add it to any part you like, but to keep things looking relatively uncluttered, I’ll dock it in the bottom part of the inspector. Your UI should now look something like this:

Unity UI with Console

Before we move on, make sure the “Clear On Play” button is highlighted in the Console pane ( See the screenshot! ). This means all messages will be cleared whenever we test our project!

I’ll briefly explain the purpose of all these tabs without boring you:

Scene / Game View

You can see there’s a window that allows us to change between the Scene View and the Game View. The scene view is for arranging objects in your scenes (or levels), and the game view is like a mini simulator for testing your game.

Hierarchy Pane

The Hierarchy Pane is an organised list of every GameObject in the current scene (level, frame, however you want to think of it). It can include cameras, 3D objects, sounds, and more. I’ll talk a little more about these “GameObjects” and how they work a little later.

Project Pane

The Project Pane is the collection of files and folders that make up the “Assets” of your game. Think of these as the RAW files for pictures, 3D models, audio clips, etc. they represent a real folder inside of your project, that Unity keeps track of and makes accessible to the rest of your game.

Inspector Pane

The Inspector Pane allows you to edit items on a per object level. If you click on an asset in the project pane, you’ll likely see import settings for it in the inspector. If you click on an object from the hierarchy, you’ll be able to edit your gameObjects. Think of this as the area where you edit stuff.

Console Pane

The Console is an area where Unity will throw errors when something has gone wrong, or give you information about particulars under the hood. What’s really cool about the console, is that you can send your own messages there too! This is most often used to “debug” your game. The console is going to be your best friend when you start getting deep into Unity. As a matter of fact, it’s going to be your friend right now too! As that’s one of the main places we’ll be focusing on for your first project!

… OK, the Unity UI is ready for our first ever project.. Let’s do this! =)

Your First Unity Project

We’re now going to create our first script! In the Project pane, click on Create and select Javascript. Then name the file “HelloConsole” without the brackets! =)


If we double click the HelloConsole file, it should open up in your default scripting application (this can be changed in Unity’s preferences, but I think you’ll be using MonoDevelop by default .. Either way, doesn’t matter too much!)

Your HelloConsole.js  script

A default javascript (or UnityScript) file in Unity is setup like this:

#pragma strict

function Start () {


function Update () {


.. What the hell does this all mean? LOL

Scripting can be quite scary when you first start looking at code, but if you take a deep breath, and take it line by line .. It soon starts to make sense, and soon after that you’ll be able to craft it into something of purpose, and the next step after that .. Is to turn the idea in your head into working programs! =)

.. But, first thing’s first ..

#pragma strict is a special command that tells Unity that we’re going to be writing javascript with a “strict” style of programming. Without getting too technical, what this means is that we’ll be creating scripts with the proper syntax, which will then allow the code to run a little faster. This is something particularly useful for mobile games ( You can remove this line, but I wouldn’t recommend it unless you know what you’re doing!)

Start() is a function with a special purpose. It is run once when the level starts .. We’ll be working here for this project! =)

Update() is a special function acting as a loop, which allows us to run code on every frame .. Usually this would be upwards of 30 frames per second, often used as your main game loop. We don’t need to worry about this too much right now.

You can see that Start and Update have a “()” after their names. This indicates that this section of code  is a “function”. I’ll talk about functions more in future parts of this tutorial. After the “()”, we have an opening curly bracket and a closing bracket on the next line “{}”, this is where we would add code to the function. That last bracket “}” tells Unity that we have no more code for the function, and its safe to end it there.

We don’t actually need the Update function, so we can safely remove it. What you should be left with is this:

#pragma strict

function Start () {


Adding Some Code

Now we can write some code into the Start function, which means it’ll get run before anything else happens. So, we’ll be sending a little message to the Console .. Add this line into your code so that the whole script looks like this:

#pragma strict

function Start () {

print(“Hello Console!”);


Just to quickly take a look at what we’ve written, we’ve told Unity to “print” some text to the console, and the text we’re printing is “Hello Console!” wrapped in parenthesis (brackets). Practically every command you write in programming needs to end with a semicolon (;) and that closes off this line and tells Unity we’re done telling it what to do.

Save the file and go back to the Unity editor.

Hooking Up The Script

Practically all scripts you write in Unity need to be attached to a “GameObject” in the Scene for it to work. So, let’s create a new empty GameObject. We can do this easily by going to the menu and selecting “GameObject > Create Empty”. Your project should look like this:

Unity UI With Empty GameObject

You can see the new GameObject in the hierarchy. In Unity, GameObject’s are base objects built up of components (scripts). If you select it you can see in the inspector it already has a component attached to it called a “Transform”. This component allows you to move the object around in 3D space, rotate it, etc. ALL gameObjects have this component and is the only one that cannot be removed.

Now we’re going to get into what makes Unity really cool to work with .. Just like the GameObject already has a Transform Component, we can also add our new HelloConsole script, and that will then show up as another component of this particular gameObject! =)  So lets add the script by dragging the “HelloConsole” file from the project pane, on to the “GameObject” in the Hierarchy pane (If you can still see it’s inspector, you can also drag straight into that too! ).

Your project should now look like this:

Unity UI - Adding Hello Console Script

You can see that the Hello Console script has now become a “Component” of the GameObject! As some of you may have guessed, this means that we can re-use this script on as many different objects as we want, and that is one of the most awesome parts of working with Unity because it lets you recycle the code you’ve written ( NOTE: it wouldn’t really make much sense doing that with this particular script, but just know that you can! lol )

OK, if we press the big “Play” button in the Untiy window, we can test the project! =)

Unity Play Button

Moment Of Truth

Awesome! In the console, you can see that we’ve sent a message saying “Hello Console!”

Unity Hello Console!

So that’s pretty cool, right? If we double click on where it says “Hello Console!” in the console pane, it will open up our scripting editor and actually show us the line of code where this came from! You would see something similar to this in your scripting program:

Unity Hello Console Selected

So that means that when you start to create more complex scripts and you’re having problems, you can add these “print” functions in your own code to help you find where things have gone wrong, or you can simply use them to inform you of things going on in the background without the user ever having to see it in the game. It’s VERY useful stuff, and will be a core technique of how to develop great projects!


I know we don’t actually have anything that remotely resembles a game, but what we do have at this point is some familiarity of the Unity UI, a very quick look at creating and writing simple scripts, an idea of how to build up our scripts by adding them to GameObjects as components, and also how to send messages to the console, which will act as the foundation for how to build and “debug” your future projects! This is the beginning of something much larger! =)

In the next tutorial, I’ll be talking about “variables”, and we’ll expand our current project by using them!

I hope you guys found this useful!

All the best,

– Mel

What Is Code Optimization? Why Do I Need It?

Being a good games programmer doesn’t just mean you understand how to make something happen in a game, it means making something happen in the most efficient way possible. Even more so for mobile development where resources are limited! As many of you know, this is often a lot harder than it sounds. I’ve decided to share some of the insights I’ve learned about code optimization that aren’t always so obvious, in the hope that it helps you to build a game that’s smoother and cooler!

What Is Code Optimization And Why Do I Need It?

GearsThe tech answer from Wikipedia, says:

In computer science, program optimization or software optimization is the process of modifying a software system to make some aspect of it work more efficiently or use fewer resources. In general, a computer program may be optimized so that it executes more rapidly, or is capable of operating with less memory storage or other resources, or draw less power.

So what does this mean? In it’s most basic form, it means don’t try and figure something out the hard way if you don’t have to. In terms of how a computer works, everything you tell it to do requires Resources ( for the most part this will be Memory / RAM ) and  processing power ( The computer’s processor and usually the graphics card’s processor too ). Usually, the more complicated / long-winded your code is, the more resources and processing power it will take for the computer to complete.

An Overly Basic, Human Example

People say the human mind is like a super-computer. Let’s say someone asked you how often you went to visit your family every week. And for the sake of argument let’s say you went every Monday and Wednesday…

Most people will probably figure it out like this inside their head:

“I know there are 7 days in the week, Monday and Wednesday are 2 of those days .. So therefore I go twice a week. The answer is 2.”

If this was programmed, it could be expressed like this:   ( 7 / 7 ) * 2 = 2;

A longwinded (and very silly) way of figuring this out would be like this:

“I know there are 365 days in a year, and that is equal to around 52 weeks, of those 52 weeks I go every Monday and Wednesday, so that makes it 104 when I multiply those together .. So if I divide the number of visits I made every year by the number of weeks in a year, that makes it 2.”

In programming, that thought process would look like this:

numberOfWeeksInYear = Round( 365 / 7 );      (equals 52)

numberOfVisits = numberOfWeeksInYear * 2;    (equals 104 )

numberOfVisits / numberOfWeeksInYear = 2;


Technically, both methods are correct because they arrived at the same answer. But It’s pretty clear the first method was going to take far less time for you to figure out, which allowed you to move on with your life and go get a milkshake or something!

In Code Optimization the same idea applies, the faster the computer can figure something out, the faster it can move onto something else. In games, this will directly impact your FPS ( Frames Per Second), which is how many times the screen gets updated every second. The more times it updates, the smoother your game will look! =)

I hope this article explains the importance of code optimisation!


– Mel


Post Brutal – Attack And Adrenaline Ability Engine Test


This is the second public development video of my own personal project made with Unity, “POST BRUTAL”.

Quick Background

It’s a 3D Action-RPG based in a Post Apocalyptic and Brutal environment ( .. The title makes sense now, right? ). It finds you struggling to survive in a city cut off from the rest of the world, plagued by a virus that turned the majority of the population into a zombie-like state. Unlike the typical zombie genre, the zombies aren’t the real threat, the rival factions in the city aspire to take control while external governmental influences complicate your survival even further..

In This Video

In this development video, we get a glimpse of the real time combat engine, allowing you to switch between a single melee and ranged weapon from your inventory ( the inventory will be shown in a later clip ) and literally cutting down wave after wave of zombie with gorgeously crazy gore! Limbs get torn off, heads are decapitated and blood rains down! We also activate the “Adrenaline Rush” ability, which slows down time in a matrix style effect that allows us to withstand damage for a limited time and get up close and personal with our melee weapon of choice! More abilities will be available depending on the type of character you have, such as a stealth ability allowing you to become invisible for a short time ( also coming up in a future video! ).


This video is in fact already out-of-date, we’re about 2 months ahead of this video, so much of the AI is vastly improved!

There’ll be way more videos to follow! If you like the vid, please let us know and show your support! =)


– Mel

Unity Tricks – An Easy Way Of Optimizing Performance In Update()

UPDATE / DISCLAIMER: This solution isn’t likely to work as well in newer mobile titles as physics is much more widely used than it used to be. Back in the old days, I wasn’t using much physics at all but things have changed over the years. In any case, FixedUpdate isn’t a great option for using slower loops anymore.  I’ll have a new and updated article about timed functions soon to replace this post! – Mel

Merry Christmas! =)

So, I thought I’d write a Christmas blog about optimizing the Update Function in a really easy way that even a Unity beginner can implement. As I’m sure that some of you hardcore people out there will probably be coding today, you may find this information useful!


Moving on .. I think most Unity beginners and even some more experienced users really put too much into their Update() method. When we’re learning the software, we kind of get psychologically used to putting things in the Update function and we like to think of FixedUpdate() as this weird scary Physics loop that we don’t quite understand and don’t want to touch.

About Unity’s Update Loops

The first thing to realize is that the standard Update function as well as LateUpdate are quite performance hungry. This is because Update usually runs at around 30 – 60 times per second ( depending on your FPS setting ), whereas FixedUpdate is set to run at fixed intervals. By default, the difference isn’t very noticeable. But, Unity allows you to tweak FixedUpdate to run at exactly the rate that you want.

An Unconventional Solution

If your game isn’t dependant on silky smooth real-time physics, you can SLOW DOWN the FixedUpdate loop which will essentially allow you to run your code less often and typically boost your FPS. A trick I use a lot for my AI routines ( especially on mobile ) is to slow down this rate for a massive FPS boost. All you need to do, is swap out the code from the Update function, to the FixedUpdate function!

How To Tweak FixedUpdate

You’ll find this inspector in the Unity Time Manager.


The above are the default values. The “Fixed Timestep” variable is set at 0.02 ms, which means it will run 50 times per second out of the box. That’s no good, especially on mobile that’s way smoother than it needs to be. If you’re using a lot of physics in the game you’ll need to play with Fixed Timestep to get a balance between smoothness and performance. I find that 0.04 is a pretty decent middle-ground for mobile devices ( which equates to around 25 times per second ). If you’re pushing more for 0.05, that will make FixedUpdate run at 20 times per second!

Update Performance

What this ( theoretically ) means is:

FixedUpdate @ 0.04 (25 TPS) vs 30 FPS Update = 16.7% boost!

FixedUpdate @ 0.05 (20 TPS) vs 30 FPS Update = 33.3% boost!

FixedUpdate @ 0.04 (25 TPS)  vs 60 FPS Update = 58% boost!

FixedUpdate @ 0.05 (20 TPS) vs 60 FPS Update = 66.7% boost!

* TPS = Times per second, FPS = Frames Per Second


There are other ways to split up your code ( that I may cover in future posts ) such as to use timed functions, create specialist manager objects, etc. But this is usually something that helps on many CPU intensive tasks like AI, Pathfinding, Updating Distances, etc. Think about if you really NEED to put your code in Update. Is it really necessary to update something 30+ times per second? .. Or is 20 times ( or less ) per second just as good? … The results may surprise you! =)

I hope this helps some of you!

All the best,

– Mel

Post Brutal – Unity3D Mobile Game Inspired By Zombies, Fallout and Dues Ex!


This is the first public showcase of my own personal project made with Unity, “POST BRUTAL”.

It’s a 3D Action-RPG based in a Post Apocalyptic and Brutal environment ( .. The title makes sense now, right? ). It finds you struggling to survive in a city cut off from the rest of the world, plagued by a virus that turned the majority of the population into a zombie-like state. Unlike the typical zombie genre, the zombies aren’t the real threat, the rival factions in the city aspire to take control while external governmental influences complicate your survival even further.. The storyline get’s a lot deeper but we’re holding that back for now! =)

The greatest thing about Post Brutal is a feature set that we can’t yet share. We’re keeping it TOP SECRET because we think it’s going to be ground breaking! Not just for a mobile game, but for video games in general!

The great thing about Unity3D is that it enables independent small teams and even single developers to create commercial quality titles. There are 2 more people on the team helping me with the non-technical areas of Post Brutal. Development is coming along nicely. What I can show you is some early engine videos, starting with this one that showcases some of the early zombie AI (which has since been vastly improved!), the cool stealth / detection system, and a glimpse of the attack systems. There’ll be way more videos to follow! If you like the vid, please let us know and show your support! =)


– Mel

Mip Maps Are Over Rated In Unity3D, Save 33% Texture Memory!

Flight Unlimited Las Vegas

So, there are definitely people on both sides of the Mip Maps fence. But I’ll throw my opinion into the mix, which is on modern mobile devices right now, Mip Maps are on the most part over-rated.

The Issues

In the screenshot above taken from the Flight Unlimited Las Vegas Unity project, you can see the negative effects of NOT having Mip Maps enabled. in the far distance of the city, things seem a little more pixelated.

If you really HAVE to use Mip Maps, a better solution is to mix and match. For example, the desert area in the background DOES have mipmaps enabled because it is a single repeating texture for a massive space around the city. This makes sense, and is worth the extra memory usage for a SINGLE texture.

By turning on Mip Maps, the scene will look a little more blurry far away ( which sometimes looks better ), but this has a cost of around a 33% extra memory.

The Math

Now consider this, in the scene above, there is around 200 textures being used. If for example, each texture WITHOUT Mip Maps were 64k in memory each, that would equal 12,800k ( About 12.5MB ).  Turning ON Mip Maps would add around 33% extra memory (on a 512×512 texture) bringing the memory cost to 85.4k each. The memory would then equal 17,080k (16.7MB). That’s around a 4MB difference. That might sound insignificant when thinking about consoles or the Desktop, but on a Mobile device, that can make all the difference!


Mip Maps are definitely something to think about. If you are going to use Mip Maps, consider if you REALLY need them. Memory is a valuable commodity in mobile development, so use it wisely! =)


– Mel

Save 50% Memory From 3D Meshes in Unity

So this is a pretty awesome optimisation I discovered while I was working on Flight Unlimited Las Vegas.


The Problem

The game has a massive part of the Las Vegas area satellite-imaged as part of the flying area. In fact, it is over 130 square miles! This really causes problems on mobile devices as RAM is limited.

I did the usual things when trying to optimise memory usage. Reduced texture sizes for smaller objects, turned off mip-maps (more on that in a different post!), etc. Then I checked out the Profiler to discover something pretty interesting ..

The actual 3D meshes ( NOT the textures ) were taking up the vast majority of the RAM. I found this pretty shocking at first as most of the buildings in the game were pretty low poly. I guess the sheer amount of them stretching over 130 virtual square miles was enough! The meshes alone were taking around 40MB of RAM.

The Solution

After thinking about what might be causing this, I did something insanely effective that I’m sure many of us would skip or not think twice about.. Disable the NORMALS and TANGENTS from the Mesh.


This has certain side-effects, but luckily, none of them applied to our project.

Normals are a type of data stored in the mesh to help out real-time lights, and Tangents are used to help Shaders perform things like “bump-mapping”.

As the scene was already baked with BEAST light-mapping, the scene wasn’t going to need the normals. And the shaders we used for the environment weren’t using bump mapping so the tangents weren’t a problem either.

The result …?

Mesh Memory was brought down from 40MB to about 23MB. Almost a 50% reduction. This was the difference between iPod4 / iPad1 compatibility, which we were able to offer upon discovering this optimisation.

I’m sure some of you should find this helpful! =)

All the best,

– Mel.

Localized Dialogs – My First Commercial Plugin For Unity

So, probably not the best idea to start this blog with a shameless plug of my own plugin, but here we go!

Anyway lol .. One of the problems I had while I was programming Ninja Guy was managing cutscenes. The even bigger issue, was how I was going to deal with the endless spectrum of different screen resolutions found on Android as well as the iOS and the Desktop versions. Creating separate builds was definitely on the table, but for a small team, that wasn’t a productive solution. I was the only programmer ( as well as UI designer, music composer and even occasional voice actor! lol ), so we needed something solid that was going to allow us to build the entire game, and be scalable enough to be ported to any resolution and platform.

After much thought and development time, the result was the Localized Dialog System. An all-in-one plugin that handled all the language localizations, GUI scaling and even an insanely easy to use editor that allowed us to basically design the conversational cutscenes visually like a flow-diagram. It required no extra coding at all, making it accessible to the rest of the team via point and click. This saved us an incredible amount of time, and this system is now available on the Unity Asset Store for everyone to take advantage of.

I even took the liberty of recording a tutorial video that explains how to use the system!


Asset Store Link

Hopefully some of you will find this useful! My next post will be about saving tremendous amounts of RAM from 3D Meshes! =)


– Mel