Tutorial 0: Unity3D and C# scripts - basics

Introduction:

I will be honest, I am not the best programmer. It can be sometimes wrong, if I am trying to explain something about C# scripts. Here I will talk about basics of C# scripts in Unity3D.

C# is an simple programming language. Ok, it's not so easy. It's easy to learn, hard to master language. But you can do good games with only basic knowlege about C#. C# is an object-oriented programming language. This will help to manage your game. Instead of making one big and hard to understand script, you can make some small objects, wich can communicate together. The objects will be like building block, with them you can build your game. There is class in C#, wich is a template for an object (in C# you can define class with line class Name {};). It is easy to define class in Unity. You should create new C# Script and name it. Now yow will have one class which name is similar as script name. You can use this script as component for Unity gameobjects.

Little example:

As example you will make an easy space shooter game. Something like next picture:
game picture
In Unity editor this will be the scene with many gameobjects: background, stars, camera, enemy, asteroid, player... Every object in your game is a GameObject. And the GameObjects are builded from Components. Some components are predefined in Unity and are ready to use. As example: Transform (working with GameObjects world position), Sprite Renderer (you can see your sprite in the game world), UI Text (shows text in interface) and many other components. And C# scripts will be components in Unity, which can be connected to the GameObjects. The C# scripts can access on other components.

How we can use C# scripts ?

At first we can create empty GameObject in scene. A gameObject will be created. This GameObject will already have the Transform component (every GameObject in Unity has Transform component). The created GameObject does not have a rendering component, so we can not see them in the game. We should add another component Sprite Renderer. And set our asteroid image as rendered sprite. So we can can see the asteroid in the game.
object asteroid
And now we can make a C# script for our asteroid.
Again, it is not game tutorial. Just let us talk about C# scripts.
We should create new C# script and name it (something like "Moving", because we will move our asteroid). If we open the created script, we will see next template:
using UnityEngine;
using System.Collections;

public class Moving : MonoBehaviour {

// Use this for initialisation
void Start () {
}

//Update is called once per frame
void Update () {
}
}
Little explain about lines:
Using UnityEngine; With this line we can access on UnityEngine namespace. Namespace in C# is collection of classes (something like a library).
using System.Collections; Here we can access on Microsoft .NET namespace.
public class Moving : MonoBehaviour { public means, that we can access on our class from other class. class Moving is our classes name. MonoBehaviour is the base class, we need them for many functions (like "Update", "Start"). Check Unity Documentation for details.
// Use this for initialization This line is just comment. It isn't important for C#.
void Start () {} void means, that our function return no values. Start () {} this function will be executed once at scene start.
void Update () {} This function will be executed every frame.

Now we will put our asteroid in the middle of the game world. The gameobjects position will be defined in Transform component (every GameObject has the transform component). We should add our Moving script to the asteroid. From our script we can change variables in transform component, which controls gameobjects position.
component screenshot

We will put our asteroid in the middle of the game world only once at game start.

Basically, if you will access on other component, you should do next steps:

1. Find other GameObject: and reference it: there are different ways to achive that.
- You can use GameObject.Find ("Name") / GameObject.FindWithTag ("Tag")
- make reference from editor with public GameObject;.
- You can get the GameObject from one Unity function like (Trigger, Raycast,...).
- Don't forget, you don't need to search for GameObject, if your script is on the same GameObject .

2. Get its Component with gameobject.GetComponent < ComponentName > (); or GetComponent < ComponentName > (); if on the same GameObject.

Transform component:

There is an easy way to access on the Transform component, if the component (our script) is on the same GameObject. Just type transform. in the script (be careful, this is working only with own Transform component. You should use GetComponent for all other components).
Position in the game world is Vector (x,y,z). If we will put asteroid in the zero point, we should change this vector to (0,0,0). C# line will be:
transform.position = new Vector3 (0, 0, 0);
We will do this only once at start, we should put this line in void Start () {}. And our script will be:
using UnityEngine;
using System.Collections;

public class Moving : MonoBehaviour {

// Use this for initialisation
void Start () {
//change gameobjects position
transform.position = new Vector3 (0, 0, 0);
}

//Update is called once per frame
void Update () {
}
}
If game is started now, our asteroid will be teleported to zero in the world.
Look again at the Transform component:
transform component
Use transform. to access on Transform component on the same GameObject. And then you can change Position, Rotation, Scale (example: transform.localScale = new Vector3 (0.5F, 1, 1);). Your IDE will help you by typing, and you can see what you can change.
C# editor screenshot
Don't forget you can get the values from other component too.

Let us now work with an other component. We have a Sprite Renderer connected to the asteroid.
spriteRenderer component screenshot
Now we will flip once at start the sprite on y-axe. We don't need to find GameObject (because our script is on the same GameObject). We can change Y-flip-variable direct with GetComponent < ComponentName > ().. For component name just check the GameObject Inspector (the name will be without spaces). The C# line will be:
GetComponent < SpriteRenderer > ().flipY = true;
And the script will be:
using UnityEngine;
using System.Collections;

public class Moving : MonoBehaviour {

// Use this for initialisation
void Start () {
//change gameobjects position
transform.position = new Vector3 (0, 0, 0);
//access to renderer component and change boolean variable, which controlls Y-flip
GetComponent < SpriteRenderer > ().flipY = true;
}

//Update is called once per frame
void Update () {
}
}
Again, your IDE will try to show the posible options.
C# editor screenshot
Sometimes, if you are working much with other component, you should make reference to it (like link). You should define the variable, which has the typ as linked component (just name from linked component). Then reference it to other component with GetComponent < ComponentName > (). And later you can use this reference variable.
using UnityEngine;
using System.Collections;

public class Moving : MonoBehaviour {

//declare reference variable for renderer component
SpriteRenderer sr;

// Use this for initialisation
void Start () {
//change gameobjects position
transform.position = new Vector3 (0, 0, 0);
//reference to renderer
sr = GetComponent < SpriteRenderer > ();
//change boolean variable, which controlls Y-flip
sr.flipY = true;
}

//Update is called once per frame
void Update () {
}
}
And we can access to component on an other GameObject.
At first we need reference to other GameObject. As said, there are many ways to access on other GameObject. As example, we have other GameObject in scene. Its name is Ship and its tag is Player (Tags are used for GameObjects identfication).
Unity Editor screenshot

1. If GameObject is in the scene at the game start, we can define public variable playerShip (typ GameObject) in the asteroids Moving script and assign the ship to the variable (just drag&drop GameObject on variables field in inspector). Now we can access on Ships components from our asteroids script. As example, we will place the ship on position (1, 1, 0) in the world at game start. The C# line whould be:
playerShip.transform.position = new Vector3 (1, 1, 0);
using UnityEngine;
using System.Collections;

public class Moving : MonoBehaviour {

//declare reference variable for renderer component
SpriteRenderer sr;
//public reference variable for players ship
public GameObject playerShip;

// Use this for initialisation
void Start () {
//change gameobjects position
transform.position = new Vector3 (0, 0, 0);
//reference to renderer
sr = GetComponent < SpriteRenderer > ();
//change boolean variable, which controlls Y-flip
sr.flipY = true;
//get access to players transform component and change its position
playerShip.transform.position = new Vector3 (1, 1, 0);
}

//Update is called once per frame
void Update () {
}
}
Unity Editor screenshot

2. We can find other GameObject in scene and assign it to our varible with GameObject.Find ("Name") or GameObject.FindWithTag ("Tag"). C# line whould be:
playerShip = GameObject.Find("Ship");
or:
playerShip = GameObject.FindWithTag("Player");
Find with tag is more efficient as find with name. And our script whould be:
using UnityEngine;
using System.Collections;

public class Moving : MonoBehaviour {

//declare reference variable for renderer component
SpriteRenderer sr;
//public reference variable for players ship
public GameObject playerShip;

// Use this for initialisation
void Start () {
//change gameobjects position
transform.position = new Vector3 (0, 0, 0);
//reference to renderer
sr = GetComponent < SpriteRenderer > ();
//change boolean variable, which controlls Y-flip
sr.flipY = true;
//searching for players ship in scene and reference it
playerShip = GameObject.FindWithTag("Player");
//get access to players transform component and change its position
playerShip.transform.position = new Vector3 (1, 1, 0);
}

//Update is called once per frame
void Update () {
}
}
And don't forget: use GetComponent < ComponentName > ();, if you will access on different component as Transform. As example, if you will flip ships sprite on X-axe from asteroid script, the line whould be:
playerShip.GetComponent < SpriteRenderer > ().flipX = true;
using UnityEngine;
using System.Collections;

public class Moving : MonoBehaviour {

//declare reference variable for renderer component
SpriteRenderer sr;
//public reference variable for players ship
public GameObject playerShip;

// Use this for initialisation
void Start () {
//change gameobjects position
transform.position = new Vector3 (0, 0, 0);
//reference to renderer
sr = GetComponent < SpriteRenderer > ();
//change boolean variable, which controlls Y-flip
sr.flipY = true;
//searching for players ship in scene and reference it
playerShip = GameObject.FindWithTag("Player");
//get access to players transform component and change its position
playerShip.transform.position = new Vector3 (1, 1, 0);
//take players ship variable, access to its renderer component and change boolean variable, which controlls X-flip
playerShip.GetComponent < SpriteRenderer > ().flipX = true;
}

//Update is called once per frame
void Update () {
}
}
3. We can get our GameObject as return value from different Unity functions. I will explain some of them later in tutorials (as example: OnTriggerEnter2D (Collider2D otherCollider) {} Then we can get GameObject from otherCollider variable).

As you can see, creating a game in Unity is just working with variables in the components of gameobjects (I am not talking about creating music, models, texts ... It is a completely different story). Now we can take a look at the basics of C # scripts. The description will be short and will affect only the basic parts. You can google for details or ask in the forums.

C# scripts - basics:

1. Variables:

Variables are named memory areas that store different information. You will work with variables, it is better to know their main types:

2. Reference variables:

As you can see from the description, such variables do not store values, but only references to memory areas. As an example, if you have a variable for gameobject with a "player" and you assign to it the "enemy" object, then your "player" will be not destroyed, you will just change the reference to another object in this variable. The object pointed to by this reference is a class with a name by type of variable. So you can create a reference variable for components and objects in Unity. The main use of such variables in Unity is access to object/component or to its functions and variables. As example:

3. Arrays (static and dynamic):

An array is an ordered data structure consisting of elements of the same type. Arrays can be not only one-dimensional, but multi-dimensional. All elements of the array are indexed, for purposeful access to them. A static array has a certain size (the number of elements) that can not be changed after the declaration. The size of the dynamic array can be changed. The indexing of the array begins with 0 (the first element of the array has the index [0]).

4. Access Modifiers:

In C # variables can be at different levels of access.

5. Areas of visibility (actions) of variables:

The location of the variable declaration determines its visibility in the containing script.

6: Arithmetic Operators:

Various arithmetic operations are possible with variables containing values. Here I will give only basic examples.

7. Mathematical Functions:

In C #, there is an Mathf structure for various mathematical functions. Check Unity Documentation for description.

8. Conditions and Boolean Operators:

For choosing another version of the execution programs have different conditional operators.

9. Loops:

Loops are used to repeatedly execute certain tasks (code fragments).

10. Functions:

A function is a separate piece of code to perform a specific task. The function can be called many times in those cases when it is necessary to solve this problem. This avoids repetition of the code. Functions can be either made by you individually for the achievement of your goals, or by preparations from Unity for standard solutions. Functions are part of the classes. Functions, like variables, have different levels of access. public functions can be accessed from other classes, access to private functions is possible only within their containing classes. For the functions to work, you may need input data - arguments (functions can also use global variables of their containing classes). After its work, the function can return some result (use Return to return the result). The type of the function must match the type of the result to return. There are also functions that do not return a result, such functions have the type void .

11. Events:

Events are similar to functions, only their launch is tied to various events. I will give just a few examples.

Only the basics of C # scripts were shown here. For a more detailed description of the individual parts of C # scripts, see the following tutorials.

Reklame: