Beginner's Scripting Guide

From Unify Community Wiki
(Difference between revisions)
Jump to: navigation, search
(Completely re-wrote this article with CSharp as the target language. Intending to add more for a more formal approach.)
m (Nested Loops)
Line 63: Line 63:
 
===== Nested Loops =====
 
===== Nested Loops =====
 
It is possible to nest loops inside each other. This means we could have multiple loops running inside. This may be useful if you want to mess with a “2D array”, which would look like this:
 
It is possible to nest loops inside each other. This means we could have multiple loops running inside. This may be useful if you want to mess with a “2D array”, which would look like this:
<syntaxhighlight lang=”csharp”>
+
<syntaxhighlight lang="csharp">
 
for(int a = 0; a < 3; a++) {
 
for(int a = 0; a < 3; a++) {
 
     for(int b = 0; b < 3; b++) {
 
     for(int b = 0; b < 3; b++) {

Revision as of 22:24, 7 April 2016

Contents

Introduction

In this portion of Beginner's coding in Unity, we will handle using the CSharp language. This is because CSharp is regarded as one of the more popular programming languages. The terms used in this article will not necessarily be the "correct" or "good" term to use. It will essentially be used to get beginner coders, like you, to understand the idea I am trying to get across.

C# Syntax

The first thing you see when creating a C# script in Unity is something like this:

using System.Collections;
using UnityEngine;

What does this mean? Simply put, there are a TON of methods/functions, classes, namespaces, etc. that are created by Unity Technologies for you. These are helper functions, Math functions, Object classes (GameObject/Transform), and more. These classes were made for Unity. Therefore, they wouldn't be used within another game engine, or if you are creating an application in C#. These classes are specifically for Unity. Therefore, Unity put them in a handy "folder", which we call namespaces. A namespace is a group of classes (or 'files'). Similarly, a class is a group of methods (code). It's just a neat way to keep everything organized. Since these classes are in a namespace (which is 'UnityEngine'), we must tell the C# Script that we want to use the classes that are within that namespace, or that we want access.

On another note, you may be thinking, "Why can't I just have everything I will ever need, and not have to worry about namespaces? Then I wouldn't ever have to use 'using...'!" And the simple answer is 3 things: 1.) MonoDevelop/Visual Studio (or whatever text editor you are using) will crash, because auto-completion will try to load all the possible methods and combinations that you give it. 2.) If you do manage to get it to work, there is a lot of guessing. What if there is a method called "GetInfo()" in a class called "HelperClass", but there is also a "GetInfo()" method inside of a class called "Notifications"? Which one would we use? 3.) Unity could possibly crash. By telling Unity that we want to use those namespaces/classes, as far as I know, memory is being reserved for those classes so we know how to access them. If you have thousands of classes ready, a lot of it is useless if you aren't going to use it. But all of this is simply just a thought. Moving on!


The next thing you see is our class identifier. This tells the script what it is called, and how it can interact. It may look like this:

public class HelloWorld : MonoBehaviour {

Let's break this down: Public tells Unity that the script can be accessed outside of its own script. If we create another script, we can access 'HelloWorld' from it, because it is public. As mentioned before, a Class is a group of methods. That's all it really is. These methods can be used however you want: They could be Object classes (which we will get into later), Helper classes (which usually is an Input>Output, or helps you process information easily), and more. The name of our class must match exactly with the name of our script. If you change it, you will also have to change the name of the script. Finally is inheritance. This is why you see the ': MonoBehaviour'. We are inheriting from MonoBehaviour, which is also a class. It's just like 'HelloWorld' class, except it is packed full with goodies! MonoBehaviour is what gives us access to pretty much everything you need to get scripts to work on objects in Unity. When you inherit from a class, you can see that in Unity. In the Inspector, you may have seen '(MonoBehaviour)' in the inspector before. If you did not inherit MonoBehaviour here, you would not see your script correctly in Unity!

So, let's get to understanding basic syntax in Unity. Below is a list of various tools you will use frequently.

Loops

Loops allow us to repeat statements multiple times without having to type it over and over. The benefit of this is we can also change how many times it loops with a variable.

For Loop

A For loop allows you to loop using an index, then use that within the loop. The index is generally used to access a specific index in an array/list.

for(int i = 0; i < 10; i++) { }

In this example, we are defining our “index” to be an integer. We are calling it i. We then set its starting value to 0. We complete this ‘statement’ with a semicolon, then follow it with the test, where we repeat the loop as long as i is less than 10. Obviously, you could change this to be anything you want. The comparison symbol could be “<, >, <=, >=” and more. The 10 can also be anything, even another variable. Finally, we define the step. i++ means we want to increment i one step each time. So the first time we run through the loop, i = 0. After we reach the end of the for loop code, i = 1, 2, 3, and so on, all the way until 9, when i is no longer less than 10. At that point, the loop breaks.

While Loop

While loops are common when trying to halt your code until a condition is met, or as long as a condition is met. These are most commonly used in Unity within Coroutines. A while loop will take in a condition, and will run the code within as long as the condition is true (Note that this means the while loop will run as long as the condition inside its parentheses is ‘true’).

while(i == 1) { }

In this example, as long as some variable called i is equal to 1, the code below will run. Outside of Unity, most game developers will use a while loop as their “update” function, so code is executed every frame. If you want to execute code all the time in a while loop, no matter what, the most common approach is to do:

while(true) { }
Foreach Loop

A Foreach Loop is similar to a For loop. However, in a Foreach loop, you are not incrementing/decrementing a variable (such as an int i), but you are incrementing through a reference to an array. For example, if I have an array of strings called string[] myStrings, I can access a reference to the elements inside of that array without having to pass in an element.

Invalid language.

You need to specify a language like this: <source lang="html4strict">...</source>

Supported languages for syntax highlighting:

4cs, 6502acme, 6502kickass, 6502tasm, 68000devpac, abap, actionscript, actionscript3, ada, algol68, apache, applescript, apt_sources, asm, asp, autoconf, autohotkey, autoit, avisynth, awk, bascomavr, bash, basic4gl, bf, bibtex, blitzbasic, bnf, boo, c, c_loadrunner, c_mac, caddcl, cadlisp, cfdg, cfm, chaiscript, cil, clojure, cmake, cobol, coffeescript, cpp, cpp-qt, csharp, css, cuesheet, d, dcs, delphi, diff, div, dos, dot, e, ecmascript, eiffel, email, epc, erlang, euphoria, f1, falcon, fo, fortran, freebasic, fsharp, gambas, gdb, genero, genie, gettext, glsl, gml, gnuplot, go, groovy, gwbasic, haskell, hicest, hq9plus, html4strict, html5, icon, idl, ini, inno, intercal, io, j, java, java5, javascript, jquery, kixtart, klonec, klonecpp, latex, lb, lisp, llvm, locobasic, logtalk, lolcode, lotusformulas, lotusscript, lscript, lsl2, lua, m68k, magiksf, make, mapbasic, matlab, mirc, mmix, modula2, modula3, mpasm, mxml, mysql, newlisp, nsis, oberon2, objc, objeck, ocaml, ocaml-brief, oobas, oracle11, oracle8, oxygene, oz, pascal, pcre, per, perl, perl6, pf, php, php-brief, pic16, pike, pixelbender, pli, plsql, postgresql, povray, powerbuilder, powershell, proftpd, progress, prolog, properties, providex, purebasic, pycon, python, q, qbasic, rails, rebol, reg, robots, rpmspec, rsplus, ruby, sas, scala, scheme, scilab, sdlbasic, smalltalk, smarty, sql, systemverilog, tcl, teraterm, text, thinbasic, tsql, typoscript, unicon, uscript, vala, vb, vbnet, verilog, vhdl, vim, visualfoxpro, visualprolog, whitespace, whois, winbatch, xbasic, xml, xorg_conf, xpp, yaml, z80, zxbasic


foreach(string s in myStrings) {
    print(s);
}

In comparison, if we wanted to access an element in an array using a for loop, we’d use something like:

Invalid language.

You need to specify a language like this: <source lang="html4strict">...</source>

Supported languages for syntax highlighting:

4cs, 6502acme, 6502kickass, 6502tasm, 68000devpac, abap, actionscript, actionscript3, ada, algol68, apache, applescript, apt_sources, asm, asp, autoconf, autohotkey, autoit, avisynth, awk, bascomavr, bash, basic4gl, bf, bibtex, blitzbasic, bnf, boo, c, c_loadrunner, c_mac, caddcl, cadlisp, cfdg, cfm, chaiscript, cil, clojure, cmake, cobol, coffeescript, cpp, cpp-qt, csharp, css, cuesheet, d, dcs, delphi, diff, div, dos, dot, e, ecmascript, eiffel, email, epc, erlang, euphoria, f1, falcon, fo, fortran, freebasic, fsharp, gambas, gdb, genero, genie, gettext, glsl, gml, gnuplot, go, groovy, gwbasic, haskell, hicest, hq9plus, html4strict, html5, icon, idl, ini, inno, intercal, io, j, java, java5, javascript, jquery, kixtart, klonec, klonecpp, latex, lb, lisp, llvm, locobasic, logtalk, lolcode, lotusformulas, lotusscript, lscript, lsl2, lua, m68k, magiksf, make, mapbasic, matlab, mirc, mmix, modula2, modula3, mpasm, mxml, mysql, newlisp, nsis, oberon2, objc, objeck, ocaml, ocaml-brief, oobas, oracle11, oracle8, oxygene, oz, pascal, pcre, per, perl, perl6, pf, php, php-brief, pic16, pike, pixelbender, pli, plsql, postgresql, povray, powerbuilder, powershell, proftpd, progress, prolog, properties, providex, purebasic, pycon, python, q, qbasic, rails, rebol, reg, robots, rpmspec, rsplus, ruby, sas, scala, scheme, scilab, sdlbasic, smalltalk, smarty, sql, systemverilog, tcl, teraterm, text, thinbasic, tsql, typoscript, unicon, uscript, vala, vb, vbnet, verilog, vhdl, vim, visualfoxpro, visualprolog, whitespace, whois, winbatch, xbasic, xml, xorg_conf, xpp, yaml, z80, zxbasic


for(int i = 0; i < myStrings.Length; i++) {
    print(myStrings[i]);
}

Essentially, we will increment from 0 to the length of the array - 1 (Because an array of 10 elements has indexes 0-9. We start at 0, not 1, therefore we have 1 less ‘element number’ than the size of 10), then we will access that element by passing it into the myStrings array.

Nested Loops

It is possible to nest loops inside each other. This means we could have multiple loops running inside. This may be useful if you want to mess with a “2D array”, which would look like this:

for(int a = 0; a < 3; a++) {
    for(int b = 0; b < 3; b++) {
        print(a + “, “ + b);
    }
}
 
 
Output:
0, 0
0, 1
0, 2
1, 0
1, 1
1, 2
2, 0
2, 1
2, 2

Unity Essentials

This section is comprised of ‘essentials’ for understanding how to get basic input/output, and utilize coding features specific to Unity.

Inheritance Tree

Unity has a lot of different classes. Below is a structure of how each of these inherit from one another:

  • Object
    • Component
      • Behaviour
        • MonoBehaviour
        • Terrain
      • Transform
  • GameObject


GameObject

GameObjects are what you will most commonly used to access information from geometry in your scene. If you have multiple scripts on the same object (GameObject) in your scene, you will use methods in the GameObject class to “find” other scripts (MonoBehaviours) on your object.

Personal tools
Namespaces

Variants
Actions
Navigation
Extras
Toolbox