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

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;

Conclusion

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!

Cheers,

– Mel