Jump to content
This site uses cookies! Learn More

This site uses cookies!

armedunity.com uses cookies to improve user experience.

By continuing to use this site, you agree to allow us to store cookies on your computer.

OneManArmy

Newbie guide to Unity Javascript (long)

Recommended Posts

If you have some prior programming experience, you may want to skip ahead to functions and classes. If you're an expert, you'll probably want to avoid this thread entirely, as you'll likely be offended at how much I simplified some concepts! :wink:

If you want to run the sample code, you do need to be familiar with the Unity interface and know how to create a script and attach it to a game object. See links below.

Intro to the Unity Interface:

Please login or register to see this link.

Intro to Scripting with Unity - read sections labeled "Our first script", and "Attaching the script".

Please login or register to see this link.

Text in RED applies to Unity iPhone users only.

VARIABLES

Think of a variable as a container that holds something.

You can choose to name a variable anything you wish, as long as it contains no spaces, starts with a letter (preferably lower case), contains only letters, numbers, or underscores, and is not a reserved keyword.

Use the keyword 'var' to create a variable. Let's call our first one 'box'.

Please login or register to see this code.

There you go, you've declared your first variable! If you're wondering about the semicolon at the end, statements (commands) in Javascript must end in a semicolon.

iPhone programmers, if you declare a variable without setting it to a value, you must state what type the variable is, in this case String. Common types include String, int, float, boolean, and Array. Note that proper capitalization is necessary!

var box : String;

Of course, our box is empty, so let's set it to a value by adding the following line:

Please login or register to see this code.

Now our box contains a text string (variable type), which happens to be "apple".

Note that you can declare your variable and set it to a value in the same statement:

Please login or register to see this code.

But once it's declared, you can't declare it again.

You can, however, change it to another value (as long as the new value is the same type as the original).

Please login or register to see this code.

In addition to text strings, variables can hold numbers:

Please login or register to see this code.

This is an integer (int), which means whole numbers only... no decimal places.

But we could also do a floating point number (float), which has decimal places:

Please login or register to see this code.

Variables can also contain booleans. A boolean is simply a true/false value:

Please login or register to see this code.

We'll discuss these more later.

Notice that a variable can normally only contain one thing at a time. But we can make a variable that contains multiple things, by creating an array:

Please login or register to see this code.

This variable contains everything you need to make an apple pie!

If we wanted to view the contents of applePie, we could output it to the Unity console using the Debug command. Add this line to the code above:

Please login or register to see this code.

On play, the console should display:

apple,brown sugar,butter,pie crust

To access a single element (item) from an array, we can access it thru its index (position in array). This may seem confusing, but indexes start at 0. So index 0 is actually the first element in the array.

Please login or register to see this code.

You can actually use indexing with Strings as well. The following code displays the first character of "hello", the letter 'h':

Please login or register to see this code.

Now lets alter our variables in other ways.

We can add variables:

Please login or register to see this code.

If you add an int (integer) to a float (floating point number) the result becomes a float:

Please login or register to see this code.

Obviously, we can also subtract/divide/multiply ints and floats.

Less obvious, we can also 'add' strings. This merges them together:

Please login or register to see this code.

If we add a number to a string the result becomes a string.

We can also multiply strings.

Please login or register to see this code.

Unfortunately, we can't divide or subtract strings. There are ways to split strings and remove parts of strings, but that is a more advanced topic.

Let's wrap up our discussion on variables with incrementing numbers (changing their value by a set amount).

First, declare a variable and set it to 1:

Please login or register to see this code.

We can increment numbers various ways.

Please login or register to see this code.

The above adds 1 to our number, and it becomes 2.

But programmers are lazy, and decided this was too long. So they abbreviated it to:

Please login or register to see this code.

This is simply shorthand for number = number + 1;

But guess what? Lazy programmers decided even THIS was to long, and shortened it to:

Please login or register to see this code.

Use whichever makes most sense to you, they all do the same thing! But note that if you choose to increment by a value other than 1, ++ won't work.

++ is shorthand for += 1 only.

You can also do the same with subtraction:

Please login or register to see this code.

But for division and multiplication, you must use one of the longer forms:

Please login or register to see this code.

Note that an asterisk means multiply, a slash means divide.

IF STATEMENTS

If statements are conditional statements. If a condition evaluates as true, do something.

We can do a comparison of two values by using two equal signs, ==

"number == 10" evaluates as true if our number variable equals 10, otherwise it evaluates as false.

Note: it's important to remember to use two equal signs when comparing variables/values, but one equal sign when setting a variable to a value!

The following creates a variable and sets it to true, checks to see if the variable equals true, and if so prints a text string to the console:

Please login or register to see this code.

The above is actually redundant, since our variable 'gameStarted' is a boolean. There is no reason to check "if true equals true", just check "if true":

Please login or register to see this code.

If you're wondering why I didn't put a semicolon behind if (gameStarted), it's because technically it is only the first half of the statement. I could have written it like so:

Please login or register to see this code.

I could have also written it this way:

Please login or register to see this code.

Those brackets represent a block of code, and tell the if statement to execute anything in between... if the condition is true!

When if contains only one statement to execute, the brackets are optional. But if it contains more than one statement, you MUST use the brackets! Note that semicolons are not needed after brackets.

Please login or register to see this code.

Read the second line of code above. Remember those lazy programmers? They don't want to write

Please login or register to see this code.

When they can just write:

Please login or register to see this code.

But you know what? Why write 'not' when I can shorten that too?

Please login or register to see this code.

Yes, an exclamation point means 'not' to lazy programmers!

You can also combine this with equals, where it means "not equals":

Please login or register to see this code.

You can also check for greater than or less than:

Please login or register to see this code.

Notice the 'else if' and 'else' keywords? if the first if statement condition fails (evaluates as false), it then checks the condition under else if. If that one fails, it will check the next else if (if one is available), and finally if all conditions fail, it executes the statement under else. Again, if the 'if', 'else if', or 'else' statements contain more than one statement, each block of code must be separated by brackets.

You can also check for multiple conditions in a single statement:

Please login or register to see this code.

Above, we introduced greater than or equal to >= and the AND operator, which is two ampersand characters: &&. If both conditions are true, the statement is executed. If even one is false, the statement is not.

Note: if you want to run the above code, remember to create variables for age (int), sex (String), and buyDrink (boolean) first!

Please login or register to see this code.

Above, we used the OR operator, which is two pipe characters: ||. If either condition is true, the statement is executed. If both are false, the statement is not.

Note: if you want to run the above code, remember to create variables for engine (String), developer (String), and buyGame (boolean) first!

If can also be used with the keyword 'in'. This is generally used with Arrays:

Please login or register to see this code.

LOOPING

Looping allows you to repeat commands a certain amount of times, usually until some condition is met.

What if you wanted to increment a number and display the results to the console?

You could do it this way:

Please login or register to see this code.

And so on... but this is redundant, and there is nothing lazy programmers hate more than rewriting the same code over and over!

So lets use a For Loop:

Please login or register to see this code.

Okay, that for statement on the second line may look a little confusing. But it's pretty simple actually.

i=1 -created a temporary variable i and set it to 1. Note that you don't need to use var to declare it, it's implied.

i

i++ -how to increment loop. In this case, we are incrementing by 1, so we use the i++, shorthand for i+=1

If we're just printing 1 thru 10, our code above could be shortened. We don't really need the number variable:

Please login or register to see this code.

Just like if statements, brackets are optional when there is only one statement to execute. Talk about beating a dead horse...

We can also count backwards:

Please login or register to see this code.

Or print all even numbers between 1 and 10:

Please login or register to see this code.

We could also use a While loop, an alternative to For statements.

While executes repeatedly until a condition is true.

Please login or register to see this code.

While loops are most useful when used with booleans. Just make sure the escape condition is eventually met, or you'll be stuck in an infinite loop and the game will most likely crash!

Please login or register to see this code.

Notice the fourth line of code above? The one that starts with two slashes? This means the text afterwards is a comment, and will not be executed. Comments are useful for noting how your code works for yourself or others, for putting in placeholder text to be replaced later (as above), or for commenting out sections of your code for debug purposes.

FUNCTIONS

If you thought loops were a time saver, wait until you find out about functions!

Functions allow you to execute a whole bunch of statements in a single command.

But lets keep things simple at first. Lets define (create) a function that simply displays "Hello world" on the console.

Please login or register to see this code.

To execute, or 'call' this function, simply type:

Please login or register to see this code.

Note the parenthesis after our function. They are required, both when we define our function and call it. Also note that our function name is capitalized. It doesn't have to be, but capitalizing function names is the norm in Unity.

What if we wanted a function to say different things? We can pass a value, or argument, to the function:

Please login or register to see this code.

Above, text is the argument, a temporary variable that can be used within the function only.

iPhone programmers, you should also state what type the argument is, in this case String.

function Say(text : String){

Now when we call our function, we have to provide an argument:

Please login or register to see this code.

We can also pass variables:

Please login or register to see this code.

Another useful thing functions can do is return a value. The following function checks to see if a number is even and if so it returns true, else it returns false:

Please login or register to see this code.

When the return command is executed in a function, the function is immediately exited (stops running). Returns don't have to return a value:

Please login or register to see this code.

The Update() function above is one of the main functions in Unity. You do not have to call it manually, it gets called automatically every frame.

OVERLOADING FUNCTIONS

Functions can be overloaded. Sounds complicated, but it's really quite simple. It means you can have multiple versions of a function that handles different types of arguments, or different numbers of arguments.

To handle different types of arguments, simply use the colon : to state the type of argument being passed. Common types include String, int, float, boolean, and Array. Note that proper capitalization is necessary!

Please login or register to see this code.

CLASSES

So variables have different types, such as String and int. But what if you need a new type that does something different?

Classes are simply new types that YOU create.

Please login or register to see this code.

The above class has two class variables, or properties, name and career. You access them by typing the name of the instance (in this case, John) followed by a period and the name of the property.

You can also pass arguments when creating instances of a class. You do this by creating a constructor, which is a special function that is automatically called whenever a new instance of your class is created. This function has the same name as your class, and is used to initialize the class:

Please login or register to see this code.

Classes can have regular functions as well. Class functions are sometimes called methods. Again, you access these by typing the name of your instance followed by a period and the function name (don't forget the parenthesis). This is useful for having instances interact with one another:

Please login or register to see this code.

INHERITANCE

Classes can inherit or extend (add functionality to) another class. The class that gets inherited from is usually called the base class or the parent class. The extended class is also called the child class or the derived class.

This will be our base class:

Please login or register to see this code.

To extend this class, create a new class with the keyword 'extends':

Please login or register to see this code.

Note that we can access the base/parent class properties and functions by using the keyword 'super'.

If we create an instance of Woman and call function Walk(), both the parent and child function are called:

Please login or register to see this code.

BUILT IN TYPES AND PROPERTIES

Now you're probably wondering, "if classes, the types I create, can have properties and functions, why can't the built in types"?

They do, actually.

To convert an int to a String, use the built-in function ToString():

Please login or register to see this code.

To get the length of an Array (or a String), use the built-in property length:

Please login or register to see this code.

You can use this in a for loop. Add the following two lines to the code above:

Please login or register to see this code.

This displays the contents of our array, one item at a time.

To add an item to an Array, use the function Add():

Please login or register to see this code.

To split a String into an array, use the function Split():

Please login or register to see this code.

To get a part of a String, use the function Substring(). Substring takes two arguments, the starting index and the ending index:

Please login or register to see this code.

To capitalize a text string, use the function ToUpper();

Please login or register to see this code.

As you might expect, there is also a ToLower() function.

Please login or register to see this code.

ADDITIONAL INFO

Intro to Scripting with Unity

Please login or register to see this link.

Intro to Unity Programming on Unify Wiki

Please login or register to see this link.

Unity Script Reference Page

Please login or register to see this link.

MSDN - This is for advanced programmers. Search for JSCRIPT, as it's quite similar to Unity javascript.

Please login or register to see this link.

Head First into Unity with JavaScript

Please login or register to see this link.

Scripting Overview

Please login or register to see this link.

  • Like 7

Share this post


Link to post
Share on other sites

Intro to Unity Programming on Unify Wiki

Please login or register to see this link.

this takes me to a yahoo page saying it is invalid

Share this post


Link to post
Share on other sites

I might start a c# tutorial as well. Just so people could code both and see which one is better.

Share this post


Link to post
Share on other sites
Please login or register to see this quote.

It's just a sample, also, it's a fruit, not a company.

Share this post


Link to post
Share on other sites
Please login or register to see this quote.

so which one is beter to u

 

easy to understand

Share this post


Link to post
Share on other sites
Please login or register to see this quote.

 

As you may have noticed, I love coding in C#, so C# is definitely easier for me. BUT NOT FOR EVERYONE. Try out JS and C# and see which one is easier for you.

Share this post


Link to post
Share on other sites

Javascript has easier syntax and most tutorials on Unity3D are all in Javascript...But if you love DaBoss's help, you should try out C#!

Share this post


Link to post
Share on other sites

Coroutines are intermediate scripting level so would server no purpose here, if YOU are interested in learning coroutines, unity docs explains them best for js

Share this post


Link to post
Share on other sites

you're right, coroutines are a piece of pie, but most tutorial series' class it an intermediate since there is alot to know before you can actually use them correctly

 

Source: Please login or register to see this link.

Share this post


Link to post
Share on other sites

Wow.. I'm feeling a little like I actually have a chance in learning hot to program. Absolute great tutorial I accidentally stumblede upon it and read it anywa and I feel like this just made me want to go pro at programing!

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×