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:

UnityTutorialChapter2-Setup

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:

UnityTutorialChapter2-Setup2

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

#pragma strict

var printText : String = “Hello Console!”;

function Start () {

print(printText);

}

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!).

print(printText);

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:

UnityTutorialChapter2-AddedNewScript

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!”.

UnityTutorialChapter2-HelloVariableChangeText

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

UnityTutorialChapter2-HelloVariableConsoleMessage

 

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:

UnityTutorialChapter2-ConsoleDebug

Conclusion

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! =)

CreateJavascript

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!

Conclusion

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

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!

Gears

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.

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

Conclusion

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