Newbie guide to Unity Javascript (long)

Discussion in 'Scripting' started by tonyd, Nov 9, 2009.

  1. tonyd

    tonyd

    New Member

    Joined:
    Jun 2, 2009
    Messages:
    1,224
    This is my introduction to scripting with the Unity version of Javascript, also known as UnityScript.

    It assumes no prior programming experience.

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

    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 at the bottom of this article.


    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'.

    Code (csharp):
    1. var box : String;
    There you go, you've declared your first variable! Note that you must state what type the variable is, in this case String. Common types include String, int, float, and boolean. Note that proper capitalization is necessary! If you're wondering about the semicolon at the end, statements (commands) in Javascript must end in a semicolon.

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

    Code (javascript):
    1. box = "apple";
    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:

    Code (javascript):
    1. var box = "apple";
    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).

    When you declare the variable and set it to a value in the same statement, then declaring the variable type is optional. This is called "type inference". The compiler sees a string value, and infers that the type must be String. You can still declare the type if you want. In some cases this can make the code more clear.

    Code (javascript):
    1. var box : String = "apple";
    As far as Unity is concerned, this statement is 100% identical to the previous statement. In both cases box is a String variable containing the string "apple". Regardless of whether you declare the type explicitly or not, the variable is a String type and can't be changed to another type later.

    Code (javascript):
    1. box = "orange"; // This is fine
    2. box = 5; // This won't work, because 5 isn't a string, it's an integer
    In addition to text strings, variables can hold numbers:

    Code (javascript):
    1. var number = 10;
    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:

    Code (javascript):
    1. var myFloat = 10.5;
    Variables can also contain booleans. A boolean is simply a true/false value:

    Code (javascript):
    1. var gameOver = true;
    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. The syntax for an array type is to add left and right square brackets [] to the type. So if you want a String array, the type is String[].

    Code (javascript):
    1. var applePie : String[] = ["apple", "brown sugar", "butter", "pie crust"];
    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 these lines to the code above:

    Code (javascript):
    1. for (var i = 0; i < applePie.Length; i++) {
    2.     Debug.Log(applePie[i]);
    3. }
    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 through its index (position in array). This may seem confusing, but indices start at 0. So index 0 is actually the first element in the array.

    Code (javascript):
    1. var applePie = ["apple", "brown sugar", "butter", "pie crust"];
    2. var item1 = applePie[0];
    3. Debug.Log(item1);
    You can actually use indexing with Strings as well. The following code displays the first character of "hello", the letter 'h':

    Code (javascript):
    1. var myString = "hello";
    2. Debug.Log(myString[0]);
    Now lets alter our variables in other ways.

    We can add variables:
    Code (javascript):
    1. var number1 = 10;
    2. var number2 = 11;
    3. var total = number1 + number2;
    4. Debug.Log(total);
    If you add an int (integer) to a float (floating point number) the result becomes a float:
    Code (javascript):
    1. var number1 = 100;
    2. var total = number1 + 1.5;
    3. Debug.Log(total);
    Obviously, we can also subtract/divide/multiply ints and floats.

    Less obvious, we can also 'add' strings. This merges them together:
    Code (csharp):
    1. var string1 = "apple";
    2. var string2 = "cider";
    3. var combo = string1 + string2;
    4. Debug.Log(combo);
    If we add a number to a string the result becomes a string.

    We can also multiply strings.
    Code (javascript):
    1. var greeting = "howdy";
    2. Debug.Log(greeting * 3);
    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:

    Code (javascript):
    1. var number = 1;
    We can increment numbers various ways.

    Code (javascript):
    1. number = number + 1;
    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:

    Code (javascript):
    1. number += 1;
    This is simply shorthand for number = number + 1;

    There's an even shorter way:

    Code (javascript):
    1. number++;
    This increments the variable. That is, it adds 1. You can also write it like this:

    Code (javascript):
    1. ++number;
    These actually do slightly different things. When you use "number++", the variable is returned and then incremented. When you use "++number", the variable is incremented and then returned. So what does this mean? If you use either method by itself, it doesn't matter.

    Code (javascript):
    1. var number = 1;
    2. number++;  // or ++number
    3. Debug.Log (number);
    In this case it's basically the same as using "number += 1;". However, let's try this:

    Code (javascript):
    1. var number = 1;
    2. Debug.Log (number++);
    3. Debug.Log (number);
    You will see that Unity prints "1", and then "2". That's because "number++", as mentioned above, is returned first and then incremented. In other words, Debug.Log prints the current value of the variable, and then the variable is incremented, so it contains the value "2" after Debug.Log has used it. Let's try it the other way:

    Code (javascript):
    1. var number  = 1;
    2. Debug.Log (++number);
    3. Debug.Log (number);
    Now Unity prints "2" both times. That's because "++number" incremented the variable first before returning it. Now, this may seem kind of tricky. And it is! But the difference can be quite useful (and important) in more advanced code, so it's worthwhile to be aware of this.

    You can also do the same with subtraction:

    Code (javascript):
    1. number--;
    2. --number;
    But for division and multiplication, you must use one of the longer forms:

    Code (javascript):
    1. number = number/2;
    2. number *= 2;
    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:

    Code (javascript):
    1. var gameStarted = true;
    2. if (gameStarted == true)
    3.     Debug.Log("Game has started");
    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":

    Code (javascript):
    1. var gameStarted = true;
    2. if (gameStarted)
    3.     Debug.Log("Game has started");
    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:

    Code (javascript):
    1. if (gameStarted) Debug.Log("Game has started");
    I could have also written it this way:

    Code (javascript):
    1. if (gameStarted) {
    2.     Debug.Log("Game has started");
    3. }
    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.

    Code (javascript):
    1. var gameStarted = false;
    2. If (gameStarted == false) {
    3.     gameStarted = true;
    4.     Debug.Log("I just started the game");
    5. }
    Read the second line of code above. Remember those lazy programmers? They don't want to write

    Code (javascript):
    1. if (gameStarted == false)
    When they can just write:

    Code (javascript):
    1. If (not gameStarted)
    But you know what? Why write 'not' when I can shorten that too?

    Code (javascript):
    1. if (!gameStarted)
    Yes, an exclamation point means 'not' to lazy programmers!

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

    Code (javascript):
    1. var answer = 1;
    2. if (answer != 42) Debug.Log("Wrong question!");
    You can also check for greater than or less than:

    Code (javascript):
    1. var age = 18;
    2. if (age > 18)
    3.     Debug.Log("old enough");
    4. else if (age < 18)
    5.     Debug.Log("jailbait");
    6. else
    7.     Debug.Log("exactly 18");
    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:

    Code (javascript):
    1. if (age >= 21  sex == "female")
    2.     buyDrink = true;
    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!

    Code (javascript):
    1. if (engine == "Unity" || developer == "friend")
    2.     buyGame = true;
    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:

    Code (javascript):
    1. var names = ["max", "rick", "joe"];
    2. if ("joe" in names) Debug.Log("Found Joe!");

    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:
    Code (javascript):
    1. var number = 0;
    2. number += 1;
    3. Debug.Log(number);
    4. number += 1;
    5. Debug.Log(number);
    6. number += 1;
    7. Debug.Log(number);
    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:

    Code (javascript):
    1. var number = 0;
    2. for (var i = 1; i <= 10; i++){
    3.     number += 1;
    4.     Debug.Log(number);
    5. }
    Okay, that for statement on the second line may look a little confusing. But it's pretty simple actually.
    var i = 1 -created a temporary variable i and set it to 1.
    i <= 10 -how long to run the loop. In that case, continue to run while i is less than or equal to 10.
    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:

    Code (javascript):
    1. for (var i = 1; i <= 10; i++)
    2.     Debug.Log(i);
    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:

    Code (javascript):
    1. for (var i = 10; i > 0; i--)
    2.     Debug.Log(i);
    Or print all even numbers between 1 and 10:
    Code (javascript):
    1. for (var i = 2; i <= 10; i += 2)
    2.     Debug.Log(i);
    We could also use a While loop, an alternative to For statements.

    While executes repeatedly until a condition is true.

    Code (javascript):
    1. var number = 0;
    2. while (number < 10) {
    3.     number++;
    4.     Debug.Log(number);
    5. }
    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!

    Code (javascript):
    1. var playerJumping = true;
    2. var counter = 0;
    3. while (playerJumping) {
    4.     //do jump stuff
    5.     counter += 1;
    6.     if (counter > 100) playerJumping = false;
    7. }
    8. Debug.Log("While loop ended");
    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.

    Code (javascript):
    1. function SayHello() {
    2.     Debug.Log("Hello world");
    3. }
    To execute, or 'call' this function, simply type:

    Code (javascript):
    1. SayHello();
    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. This makes it easy to distinguish between variables and functions.

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

    Code (javascript):
    1. function Say(text : String) {
    2.     Debug.Log(text);
    3. }
    Above, "text" is the argument, a temporary variable that can be used within the function only. Note that the type of the argument must be defined. In this case "text" is a string.

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

    Code (javascript):
    1. Say("Functions are cool!");
    We can also pass variables:

    Code (javascript):
    1. var mytext = "I want a pizza";
    2. Say(mytext);
    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:

    Code (javascript):
    1. function EvenNumber(number : int) {
    2.     if (number % 2 == 0)
    3.         // NOTE: % is the mod operator. It gets the remainder of number divided by 2
    4.         return true;
    5.     else
    6.         return false;
    7. }
    8.  
    9. var num = 10;
    10. if ( EvenNumber(num) )
    11.     Debug.Log("Number " + num + " is even");
    When the return command is executed in a function, the function is immediately exited (stops running). Returns don't have to return a value:

    Code (javascript):
    1. function Update() {
    2.     if (!gameStarted) return; //exit function
    3. }
    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, and boolean. Note that proper capitalization is necessary!

    Code (javascript):
    1. function PrintType(item : String) {
    2.     Debug.Log("I'm a string, type String");
    3. }
    4.  
    5. function PrintType(item : int) {
    6.     Debug.Log("I'm an integer, type int");
    7. }
    8.  
    9. function PrintType(item : float){
    10.     Debug.Log("I'm a float, type float");
    11. }
    12.  
    13. function PrintType(item : boolean) {
    14.     Debug.Log("I'm a boolean, type boolean");
    15. }
    16.  
    17. function PrintType(item: GameObject) {
    18.     Debug.Log("I'm something else");
    19. }
    20.  
    21. function PrintType() { //catches everything else
    22.     Debug.Log("You forgot to supply an argument!");
    23. }
    24.  
    25. PrintType();
    26. PrintType("hello");
    27. PrintType(true);

    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.

    Code (javascript):
    1. class Person {
    2.     var name : String;
    3.     var career : String;
    4. }
    5.  
    6. //Create objects of type Person
    7. var john = Person();
    8. john.name = "John Smith";
    9. john.career = "doctor";
    10. Debug.Log(john.name + " is a " + john.career);
    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:

    Code (javascript):
    1. class Animal {
    2.     var name : String;
    3.     function Animal(n : String){ //this is the constructor
    4.         name = n;
    5.         Debug.Log(name + " was born!");
    6.     }
    7. }
    8.  
    9. var cat = Animal("Whiskers");
    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:

    Code (javascript):
    1. class Person {
    2.     var name : String;
    3.     function Person(n : String) {
    4.         name = n;
    5.     }
    6.     function kiss(p : Person) {
    7.         Debug.Log(name + " kissed " +  p.name + "!");
    8.     }
    9. }
    10.  
    11. jenni = Person("Jenni");
    12. bob = Person("Bob");
    13. jenni.kiss(bob);

    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:

    Code (javascript):
    1. class Person {
    2.     var name : String;
    3.     function Person(n : String) { //constructor
    4.         name = n;
    5.     }
    6.     function Walk() { //class function
    7.         Debug.Log(name + " is walking");
    8.     }
    9. }
    To extend this class, create a new class with the keyword 'extends':

    Code (javascript):
    1. class Woman extends Person {
    2.     var sex : String;
    3.     function Woman(n : String){ //constructor
    4.         super(n);  //calls the original constructor and sets name
    5.         sex = "female"; //adds additional functionality to the extended class
    6.     }
    7.     function Walk() {
    8.         super.Walk(); //calls the original function
    9.         Debug.Log("And she is so sexy!"); //adds additional functionality to the extended class
    10.     }
    11. }
    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:

    Code (javascript):
    1. amanda = Woman("Amanda");
    2. amanda.Walk();

    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():

    Code (javascript):
    1. var number = 10;
    2. var text = number.ToString();
    To get the length of a array (or a String), use the built-in property Length:

    Code (javascript):
    1. var animals = ["cat", "dog", "pig", "dolphin", "chimpanzee"];
    2. var total = animals.Length;
    You can use this in a for loop. Add the following two lines to the code above:

    Code (javascript):
    1. for (var i = 0; i < animals.Length; i++){
    2.     Debug.Log(animals[i]);
    3. }
    This displays the contents of our array, one item at a time.

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

    Code (javascript):
    1. var sentence = "The quick brown fox jumped over the lazy dog";
    2. var words = sentence.Split(" "[0]);
    3. for (var i = 0; i < words.Length; i++) {
    4.     Debug.Log(words[i]);
    5. }
    To get a part of a String, use the function Substring(). Substring takes two arguments, the starting index and the ending index:

    Code (javascript):
    1. var sentence = "The quick brown fox jumped over the lazy dog";
    2. var firstHalf = sentence.Substring(0, 19);
    3. Debug.Log(firstHalf);
    To capitalize a text string, use the function ToUpper();

    Code (javascript):
    1. var mission = "go make cool games!";
    2. Debug.Log( mission.ToUpper() );
    As you might expect, there is also a ToLower() function.

    Code (javascript):
    1. Debug.Log( ("THE END").ToLower() );

    ADDITIONAL INFO

    Online learning materials for Unity
    http://unity3d.com/learn

    Intro to Unity Programming on Unify Wiki
    http://wiki.unity3d.com/index.php/Programming_Chapter_1_Old

    Unity Script Reference Page
    http://unity3d.com/support/documentation/ScriptReference/

    MSDN - This is for advanced programmers. It typically uses C# for code examples, but nearly all of it applies equally to Javascript.
    http://msdn.microsoft.com/en-us/library/system(v=vs.110).aspx
     
    Ness and Magiichan like this.
  2. raiden

    raiden

    Member

    Joined:
    Feb 8, 2009
    Messages:
    216
    I just wanted to say I appreciate all you have put in to this post. I was understanding everything until I got to Inheritance, where did "super(n)" come from? I see no reference or why/how it's being used in either the base class or extended class.

    Thanks

    -Raiden
     
  3. KHopcraft

    KHopcraft

    Member

    Joined:
    Jun 6, 2009
    Messages:
    3,244
    You are a nice person, making a long guide to programming for newbies. Thanks for being at this community. :D
     
  4. tonyd

    tonyd

    New Member

    Joined:
    Jun 2, 2009
    Messages:
    1,224
    No problem.

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

    super simply refers to the parent/base class.
     
  5. tlass

    tlass

    New Member

    Joined:
    Mar 9, 2009
    Messages:
    19
    Thank You!
     
  6. ChrisMann

    ChrisMann

    New Member

    Joined:
    Oct 21, 2009
    Messages:
    52
    Nice post.
     
  7. GusM

    GusM

    Member

    Joined:
    Aug 27, 2005
    Messages:
    574
    Very usefull for beginners, thanks a lot.
     
  8. WinningGuy

    WinningGuy

    New Member

    Joined:
    Aug 10, 2009
    Messages:
    886
    I think this deserves a sticky.

    Thank you very much for the time and effort you put into this.
     
  9. andeeeee

    andeeeee

    Unity Technologies

    Joined:
    Jul 19, 2005
    Messages:
    8,732
    Well, we'll see about that in time, but I have added it to the Scripting board FAQ.

    Thanks for posting this Tony!
     
  10. edplane

    edplane

    New Member

    Joined:
    Jul 13, 2009
    Messages:
    485
    Wow, just what i need: a list to help me remember those tricky codes XP
    BTW, im typing this from school. HAHA! Ill study my way!
     
  11. shader

    shader

    New Member

    Joined:
    Apr 4, 2009
    Messages:
    251
    A very kind contribution.

    Thank you :)
     
  12. Goody!

    Goody!

    New Member

    Joined:
    Sep 11, 2009
    Messages:
    100
    Great stuff! Very informative! If you can, please add to you array section how to access individual things stored in an array. I don't know how to take array element1 and subtract it from array element2. For example:

    array of vextor3's

    array element2[2,3,4] - array element1[1,2,3]

    = result of [1,1,1] (somehow). :?

    Thanks again!
     
  13. Xen

    Xen

    New Member

    Joined:
    Nov 18, 2009
    Messages:
    17
    I may have misunderstood your post but if your array is an array of Vector3's then wouldn't this work ...

    var result:Vector3 = array[2] - array[1]

    (I'm a noob so i'm probably wrong)
     
  14. Xen

    Xen

    New Member

    Joined:
    Nov 18, 2009
    Messages:
    17
    Great post!

    Given your extensive knowledge of UnityScript, do you think you could folow up this great post with a list of the differences between normal js and Unity js. I have no idea how extensive the differences might be but I find myself falling into the trap of trying to use non-supported features or using features that are different in a *normal* way and crashing.
     
  15. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Messages:
    26,281
  16. Xen

    Xen

    New Member

    Joined:
    Nov 18, 2009
    Messages:
    17
    Eric5h5 - Excellent! Thanks
     
  17. helioraanswer

    helioraanswer

    Member

    Joined:
    Apr 7, 2009
    Messages:
    410
    Hi and thanks for the intro,

    I'm a 3d artist and don't know the basics, so all I do is copy paste and change numbers untill it works. But that way int's not efficient and is buggy as hell.

    If you're planning going to continue with Unity tutorials, which would be awesome so I don't have to bother programmers all the time, could you make something about movement, cameras, rotation (world/self etc.) and simple AI?
     
  18. RoyS

    RoyS

    Member

    Joined:
    Jan 12, 2009
    Messages:
    552
    Thank you for a good head start. I have hired programmers, but always felt illiterate that I couldn't script well.

    My New Year's resolution is to start learning Unity Java Script next year, so I won't be so handicapped.
     
  19. steffenk

    steffenk

    New Member

    Joined:
    Jul 17, 2009
    Messages:
    4
    thanks for the great starterguide. can i translate your guide into german and post it on the forum? that might be good for the growing number of german unity users :)
     
  20. tonyd

    tonyd

    New Member

    Joined:
    Jun 2, 2009
    Messages:
    1,224
    Feel free to translate it, just give me credit for the original document.
     
  21. shadyfella13

    shadyfella13

    New Member

    Joined:
    Aug 24, 2009
    Messages:
    4
    This was quite helpful for me as I have never touched a script before Unity. Thank you so much. :)
     
  22. Lateris

    Lateris

    New Member

    Joined:
    Jul 29, 2009
    Messages:
    1
    This has really pointed me in the right directions as a PM for our project. I want to get my hands on the engine this time around for our game. Are there any books that you suggest?
     
  23. dacresni

    dacresni

    New Member

    Joined:
    Feb 13, 2009
    Messages:
    4
    Thanks for mentioning inheritance, people learning this stuff in school especially benefit to know how to do object orientation in this form of javascript. It is important to note this for those familiar enough with javascript to know that javascript doesn't have classes
     
  24. fdslk

    fdslk

    New Member

    Joined:
    Jan 25, 2010
    Messages:
    4
    I'll take this chance to ask, why the console tells me that animation.wrapMode = WrapMode.Loop is not a legal function? I mean, I've seen in lots of examples that WrapMode.Once and Loop decides, but according to the console, both Once and Loop are not part of the WrapModes, I'm using the latest version of Unity... Can someone please explain?
     
  25. andeeeee

    andeeeee

    Unity Technologies

    Joined:
    Jul 19, 2005
    Messages:
    8,732
    No problem, but in a new thread, please.
     
  26. Davaris

    Davaris

    New Member

    Joined:
    Jan 27, 2010
    Messages:
    68
    Thanks for this tonyd!
     
  27. Mirage

    Mirage

    New Member

    Joined:
    Jan 13, 2010
    Messages:
    230
    Excellent tutorial, I will be returning here often! :oops:
     
  28. spaceMan-2.5

    spaceMan-2.5

    New Member

    Joined:
    Oct 21, 2009
    Messages:
    710
    what a fool i was, never seen before this post...

    thank you...!
     
  29. riadsala

    riadsala

    New Member

    Joined:
    Feb 10, 2010
    Messages:
    15
    +1 for this being a great post. :D
     
  30. Tiles

    Tiles

    Member

    Joined:
    Feb 5, 2010
    Messages:
    2,244
    Just curious, is it already translated? And if yes, where to find?
     
  31. dansav

    dansav

    Member

    Joined:
    Sep 22, 2005
    Messages:
    330
    This is an excellent tutorial with a light hearted feel that makes programming seem fun and easy rather than daunting and difficult.

    It is perfect for beginners who have not had any programming experience.

    Great Work

    Sincerely,

    Daniel Savage
    Teacher, Educational Software Developer funded by Department of Education
     
  32. mikesgames

    mikesgames

    New Member

    Joined:
    Apr 16, 2010
    Messages:
    1,072
    thank you for the tut!
     
  33. stonegolem

    stonegolem

    New Member

    Joined:
    May 8, 2010
    Messages:
    20
    Thank you.
    I'm a 3D modeler and I have a programming-phobia. I started to use your tutorial to fix my "JavaScript" issue.
     
  34. TheMorten

    TheMorten

    New Member

    Joined:
    Feb 17, 2010
    Messages:
    7
  35. andeeeee

    andeeeee

    Unity Technologies

    Joined:
    Jul 19, 2005
    Messages:
    8,732
    This is called the ternary operator and it actually consists of two parts, the question mark and the colon. Basically, it allows you to shortcut an assignment that you would otherwise do with an "if" statement. If you write:-
    Code (csharp):
    1. t = x > 10 ? player.transform : enemy.transform;
    ...it is equivalent to:-
    Code (csharp):
    1. if (x > 10) {
    2.     t = player.transform;
    3. } else {
    4.     t = enemy.transform;
    5. }
     
  36. jpsubbarayalu

    jpsubbarayalu

    New Member

    Joined:
    Jul 13, 2010
    Messages:
    65
    Hi,


    You did excellent work here!!!Very nice!!!
     
  37. cherub

    cherub

    Member

    Joined:
    Apr 26, 2006
    Messages:
    486
    this need to become a sticky or at least added to the links in the one already here.
     
  38. Dylan Cristy

    Dylan Cristy

    New Member

    Joined:
    Sep 14, 2010
    Messages:
    21
    Hi,

    First of all, nice post, thanks tonyd.

    Although I am not entirely new to scripting, I am a Unity noob. The previous engine I used had a very specific way of going about scripting, and now that I am (about to be) using Unity, I am learning some new concepts having to do with OOP, including the idea of classes and inheritance, and I've learned a lot already reading through the scripting reference and checking stuff out on the wiki.

    So the question I have about inheritance is this: what is the correct syntax to assign values to a variable declared in the parent class when assigning those values based on subclass (i.e. those variables will be the same for each instance of each subclass, but vary across different subclasses)?

    For example, here's a parent class:

    Code (csharp):
    1. class Vehicle{
    2.     var speedRating : float;
    3.     var armorRating : float;
    4.     function Vehicle(){
    5.             //some code here
    6.     }
    7.     function Move(){
    8.             //some code that uses the speedRating variable here
    9.     }
    10. }
    and a couple subclasses:

    Code (csharp):
    1. class Porsche extends Vehicle{
    2.     function Porsche(){
    3.             super.speedRating = 200;
    4.             super.armorRating = 30;
    5.             //other stuff
    6.     }
    7.     function Move(){
    8.             super.Move();
    9.     }
    10. }
    11.  
    12. class Truck extends Vehicle{
    13.     var cargo : String;
    14.     function Truck(c : String){
    15.             super.speedRating = 50;
    16.             super.armorRating = 175;
    17.             cargo = c;
    18.             //other stuff
    19.     }
    20.     function Move(){
    21.             super.Move();
    22.     }
    23. }
    Is that the correct syntax for assigning the "speedRating" and "armorRating" variables? Or can I get away with not putting the super in there?

    And does it make a difference if I don't call the parent constructor, even if I don't need to pass any parameters to the parent constructor?

    Also, I suppose an additional question would be, can you pass multiple parameters to constructors? Could the parent class have a constructor of:

    Code (csharp):
    1.  
    2.     function Vehicle(s : float, a : float){
    3.             speedRating = s;
    4.             armorRating = a;
    5.             //some code here
    6.     }
    and then the child constructors do this?:

    Code (csharp):
    1.  
    2.     function Porsche(){
    3.             super(200, 30);
    4.             //other stuff
    5.     }

    Thanks for any help in explaining this.
     
  39. Rush Rage Games

    Rush Rage Games

    Member

    Joined:
    Sep 9, 2010
    Messages:
    1,999
    This should be sticky! :)
     
  40. thesimi

    thesimi

    New Member

    Joined:
    Jun 16, 2009
    Messages:
    94
    truly awsome, I cant imagine how much time you spent on that
    you are officialy (I will never learn how to spell that correctly:p) SUPERAWSOME:D
     
  41. Ricks

    Ricks

    Member

    Joined:
    Jun 17, 2010
    Messages:
    631
    Thanks for this guide, especially the constructor inheritance part :)
     
  42. deram_scholzara

    deram_scholzara

    Member

    Joined:
    Aug 26, 2005
    Messages:
    952
    Wow! This is an excellent intro tutorial - and even covers some things that many people consider advanced. Very very nice.
     
  43. shunmugam

    shunmugam

    New Member

    Joined:
    Oct 19, 2010
    Messages:
    1
    hi tonyd
    thank you very much it's very useful thread for beginner starter guide... thank you very much for your post
     
  44. drewradley

    drewradley

    Member

    Joined:
    Sep 22, 2010
    Messages:
    2,118
    Thanks so much for this! It's been very helpful to me.

    The nit picker in me wants to point out that it should be "The quick brown fox JUMPS over the lazy dog" otherwise you miss the "s" but since that has absolutely nothing to do with the actual code, I won't.

    Oh wait... ;)
     
  45. Clueless11-yr-old

    Clueless11-yr-old

    New Member

    Joined:
    Nov 4, 2010
    Messages:
    20
    Thank you so much for this! I will gradually work through it, hehe, may take a while. You're really very nice to take time out to write this detailed tutorial out, hopefully it'll get me started with JS. :)

    Thanks again!
     
    Last edited: Nov 11, 2010
  46. paco

    paco

    Guest

    Joined:
    Oct 28, 2010
    Messages:
    20
    *thumbs up* thx.
     
  47. FoxGirlTheGamer

    FoxGirlTheGamer

    New Member

    Joined:
    Sep 29, 2010
    Messages:
    14
    cool! I was able to skip the first few sections 'cause they were 'my thing' but now I know a lot more about UnityScript and can't wait to get started. (And that's wonderful since I am wasting my time not getting started by writing this message. So why am I writing this message? Because I'm an idiot. Okay bye.)
     
  48. Jay_Adams

    Jay_Adams

    New Member

    Joined:
    Nov 8, 2010
    Messages:
    152
    Yeah, thanks for this, deffinately helps to understand scripting.
     
  49. schwertfisch

    schwertfisch

    Member

    Joined:
    Sep 7, 2010
    Messages:
    110
    Thanks for your post tonyd, I am a beginner and I found it really useful! :)
     
  50. MrRudak

    MrRudak

    New Member

    Joined:
    Oct 17, 2010
    Messages:
    159
    Cool thanks! great !