If Blocks in C# | Unity Tutorial

Suppose we wanted to run code only when a certain condition is met. For instance, a player could only fly in a game if they had a jet pack. A player could only buy a bicycle if they had enough money. To implement this kind of functionality, we can use if blocks. If you are a beginner and want to learn how to build virtual reality games, check out our Unity3D course!

An if block runs code when a specified condition passes. In the Start method from our previous tutorial, use the following format to create an if block.

// Use this for initialization
void Start () {
transform.name = ImproveName(newName);

if () {

}
}

The code in between the if block’s parentheses will contain the condition that needs to be met. If the condition passes, the code in the scope definition (between the curly braces) will execute.

Give the if block the following condition. The if block will execute code because 1 plus 1 equals 2.

// Use this for initialization
void Start () {
transform.name = ImproveName(newName);

if (1 + 1 == 2) {

}
}

Note that a single equals sign (=) assigns a value. A double equals sign (==) is a comparison.

Type the following code in the if block. The string “We’re here!” will print in the console if the if block’s condition is true.

// Use this for initialization
void Start () {
transform.name = ImproveName(newName);

if (1 + 1 == 2) {

}
}

Save the script, and open Unity. Press Play. The message “We’re here!” will print in the console. This means that the if block’s condition passed.

Let’s test a different condition in the if block. Use the following code to make the if block test if the string “cats” equals the string “dogs”.

// Use this for initialization
void Start () {
transform.name = ImproveName(newName);

if ("cats" == "dogs") {
Debug.Log ("We're here!");
}
}

Save the script, and open Unity. Press Play. A warning will appear in the console stating that there is unreachable code at Line 14 of Cube.cs.

This warning appears because the compiler already knows that “cats” will never equal “dogs”. Thus the compiler automatically converts the condition in the parentheses to false. The code in the if block will never be executed.

What if we want the if block to execute code only if a condition is false? Create the following if block, which will run code when “cats” is not equal to “dogs”. The exclamation mark means “NOT”.

// Use this for initialization
void Start () {
transform.name = ImproveName(newName);

if ("cats" == "dogs") {
Debug.Log ("We're here!");
}

if ("cats" != "dogs") {
Debug.Log ("We're there!")
}
}

Save the script, and open Unity. Press Play. The message “We’re there!” will print in the console.

Want to learn more about if blocks? Check out our Unity3D course, where you build 30 virtual reality games!

Changing Properties LIVE | Unity Tutorial

One of the uses of methods is changing the properties of an object live as your game runs. If you are a beginner and want to learn how to build virtual reality games, check out our Unity 3D course!

Suppose you want to change the size of the cube while the game is running. You can use the Update method to achieve this. Cut the line in the Start method. Paste it into the Update method in place of the Log line. Edit the line so that it appears as so:

// Use this for initialization
void Start () {

}

// Called once per frame.
void Update () {
transform.localScale = Vector3.one * sizeModifier;
}

In the preceding code, we set Cube’s local Scale to be the original vector (1 1 1) multiplied by sizeModifier. Save the script, and open Unity. Press Play. Cube will have the dimensions 0.1 0.1 0.1. Click on the “Size Modifier” label (text) in the Cube (Script) property, and drag your mouse left and right. Cube’s size will change according to the value of Size Modifier.

Stop playing the scene. Set Size Modifier to 2.5. Next we will change the name of the cube. Currently, you can see in the Hierarchy that the name of the cube is “Cube”. In Cube.cs, type the following line into the Start method.

// Use this for initialization
void Start () {
transform.name = newName;
}

Save the script, and open Unity. Press Play. “Cube” in the Hierarchy will be renamed “Cubey42”.

What if we wanted to define a new method other than Start and Update? Suppose we want to use a method to add some characters to Cubey42‘s name. Below the Start method, type the following code to declare the method ImproveName.

// Use this for initialization
void Start () {
transform.name = newName;
}

string ImproveName (string originalString) {

}

string ImproveName means the method returns a string. The method has the string originalString as a parameter.

Save the script, and open Unity. The Console will show the following error message.

The message states that the file Cube.cs in Assets, contains an error at Line 20 in Row 16. The error is that not all code paths return a value in ImproveName. This error occurs because ImproveName needs to return a value. Open Cube.cs. Use the following code to return 10.

string ImproveName (string originalString) {
return 10;
}

Save the script, and open Unity. An error will appear in the Console saying that an integer cannot be converted to a string.

ImproveName returns a string, but 10 is an integer. Use the following code to return originalString, the method’s parameter. + appends “-[” and “]-” around originalString.

string ImproveName (string originalString) {
return "-[" + originalString + "]-";
}

Call the ImproveName method in the Start method. The following code makes newName a parameter of ImproveName. ImproveName will edit newName to contain the string that ImproveName returns.

void Start () {
transform.name = ImproveName(newName);
}

Save the script, and open Unity. Press Play. “Cubey42” in the Hierarchy will become “-[Cubey42]-“. Want to learn more about methods? Check out our Unity 3D course, where you build 30 virtual reality games!

Methods in C# | Unity Tutorial

Games are all about action. To give your game objects custom behavior, you can use methods. If you are a beginner and want to learn how to build virtual reality games, check out our Unity3D course!

A method in a script performs an operation or function. In this tutorial, we will continue with the example in our previous post to show the two methods that appear in any C# script you create in Unity: Start and Update.

The Start Method

In the last tutorial, we deleted the methods from the Cube script to prevent confusion. Recreate the Start method with the following code.

Note that typing // in front of a line of code turns the code into a comment, which is not read by the compiler.

public class Cube : MonoBehaviour {

public float sizeModifier = 2.5f;
public string newName = "Cubey1337";
public bool isRotated = false;

// Use this for initialization
void Start () {

}
}

In the preceding code, the method name is Start. Each word in the name of a method is capitalized. The Start method is executed when the game is run.

A method can perform an operation and return the result. For instance, a method can add numbers, return the sum, and store the sum in a variable. void means the Start method does not return anything. The method can still execute operations.

In between the parentheses, you can pass any parameters of a method. Parameters make a method more specific. For instance, a method that changes the TV channel could have the number of the new channel as a parameter.

The method’s definition goes between the curly braces. The code within the braces will be executed when the Start method is called.

Printing a Message

Suppose you want to print a message in the console. Type the following code to print “Hello World!” when the Start method is called.

// Use this for initialization
void Start () {
Debug.Log ("Hello world!");
}

To call a method, you call its class, use the dot operator, type the method name, and pass the parameters in parentheses. Debug is a class that is defined in the Unity engine. The . operator accesses a method inside the Debug class. Log calls the Log method. We passed the string “Hello world!” as a parameter.

Save the script, and open Unity. To call the Start method, press Play. Open the Console. As evident in the following image, the message “Hello world!” will print in the Console.

Stop running the scene. In Cube.cs, change “Hello world!” to “Started!”.

The Update Method

The other method we previously deleted is Update. Declare the Update method with the following format.

// Use this for initialization
void Start () {
Debug.Log ("Hello world!");
}

// Called once per frame.
void Update () {

}

When a game or app runs, the smartphone or computer on which it is running updates the app constantly: processing, performing calculations, drawing pixels, sending messages, and more. The Update method executes every time a game is updated. An app running at 60 frames per second calls the Update method 60 times each second.

Type the following code into the Update method, which will print “Updating!” every time the Update method executes.

// Called once per frame.
void Update () {
Debug.Log (Updating!);
}

Save the script, and open Unity. When the compilation completes, press Play. “Started!” and “Updating!” will appear in the Console. “Updating!” will print multiple times as the Update method is called.

Select the Collapse tab from the Console. The Collapse window collapses identical messages that are printed one after the other. As evident in the next screenshot, the number to the right of “Updating!” increase every time the Update method is called.

Stop playing the scene. Let’s use the variables sizeModifier and newName in the Start and Update methods. In Cube.cs, replace the Log line in the Start method with the following code.

// Use this for initialization
void Start () {
transform.localScale *= sizeModifier
}

transform accesses the Transform component of the Cube game object. . accesses something in the Transform component, in this case the localScale property. localScale stores the scale of the cube, which is currently 1 1 1, as you can see in the Inspector.

*= sizeModifier takes the values stored in transform.localScale and multiplies them by sizeModifier, which is 2.5. In other words, the Scale values will multiply by 2.5.

Save the script, and open Unity. Press Play. Cube will be bigger than it was before. To change Cube’s size, you can change the Size Modifier property in the Cube (Script) component. For instance, if you change the value of Size Modifier to 0.1, Cube’s size will decrease.

Want to learn more about methods? Check out our Unity3D course, where you build 30 virtual reality games!

 

Variables in C# | Unity Tutorial

Variables: the building blocks of code. When building a game in Unity, you often need to store information, such as a player’s age or the current time. Variables are perfect for storing data. If you are a beginner and want to learn how to build virtual reality games, check out our Unity3D course

In this tutorial, we will use an example of a cube to show some of the useful things variables can do. We will change the size, name, and rotation of a cube using variables in C#.

To simplify this example, you can delete the following lines from the C# script we created in the last tutorial.

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {

}

Changing Size

Suppose we want to change the size of the cube we created last time. We can create a variable to store a change in size. In Unity, you can see that the default Scale values of Cube are 1 1 1. In the Cube script, you can modify Cube’s Scale values in the Cube class. Type the following bold line of code in the script:

using UnityEngine;
using System.Collections;

public class Cube : MonoBehaviour {

public float sizeModifier = 2.5f;

}

The preceding code declares a variable named sizeModifier. In C#, the naming convention for variables is to capitalize the first letter of every word after the first word.

float means that sizeModifier stores a floating-point number, also known as a float. Floats are numbers that can contain decimal places.

The public keyword means that classes other than Cube can access sizeModifier. As well, using public allows us to modify sizeModifier in the Unity editor.

To declare sizeModifier, we could have just typed public float sizeModifier;. To initialize the variable (store a value in it), we added = 2.5f.

= assigns a value to a variable. The code to the right of the equals sign will be placed in sizeModifier. 2.5f stores the value 2.5 as a float.

Save the script. Open Unity. The sizeModifier variable will be represented as the property “Size Modifier” in the Cube (Script) component. Note that the script must finish compiling before you can see changes.

To change sizeModifier, you do not need to go to the Cube script, change 2.5, and wait for another compilation. Instead, you can change the value of Size Modifier in the Inspector. As such, you can test your values faster.

Renaming

Let’s rename Cube. To store Cube’s name, create another variable in the Cube class.

public class Cube : MonoBehaviour {

public float sizeModifier = 2.5f;
public string newName = "";

}

newName is a variable of type String. A string variable is a collection of characters. The value of a string needs to be enclosed in double quotation marks. Currently, the string is empty. Use the following format to name the cube “Cubey1337”.

public class Cube : MonoBehaviour {

public float sizeModifier = 2.5f;
public string newName = "Cubey1337";

}

Save the script, and open Unity. When the compilation completes, the field “New Name” will appear in the Cube (Script) component. Here you can change the value of newName, for instance, to “Cubey42”.

Changing Rotation

Another type of variable is the Boolean. A Boolean variable can contain one of two values: true or false. Use the following code to create a Boolean variable that determines whether Cube will be rotated.

public class Cube : MonoBehaviour {

public float sizeModifier = 2.5f;
public string newName = "Cubey1337";
public bool isRotated = false;
}

The value of isRotated is initially false, which means the cube will not be rotated. Save the script, and open Unity. The property “Is Rotated” will appear in the Cube (Script) component.

Unlike the Size Modifier and New Name properties, which are text fields, Is Rotated is a checkbox. The checkbox is checked when isRotated is true and unchecked when isRotated is false.

Want to learn more about variables? Check out our Unity3D course, where you build 30 virtual reality games!

Creating a C# Script | Unity Tutorial

Do you want to customize the behavior and appearance of your game objects? You can use script to do just that. This tutorial will be the first of a series in which you will learn how to code a C# script for Unity. If you are a beginner and want to learn how to build virtual reality games, check out our Unity3D course

Setting up the Scene

Create a new project in Unity named “CodeIntroduction”. Create a cube in the Hierarchy. Give Cube the position 0 0 0 so that it is centered in the Scene.

Let’s change Cube’s color. Create a material named “ColorMaterial” in the Assets folder. In the Inspector, change the material’s color to an orange with RGB values 155 153 0.

Drag and drop ColorMaterial from Assets to Cube in the Scene to apply the color to the cube. Set Main Camera’s Z position to -4 so that it is closer to Cube.

Save the Scene as “Game.unity”. A file named “Game” will appear in the Assets folder.

Creating the Script

Every game object in the Hierarchy has components in the Inspector. Unity provides components such as materials, collisions, and 3D primitives. To create a more complex game, you can write custom behavior for an object. To this, you create a script and attach the script as a component of the game object.

In the Project window, let’s make a script for Cube. Right-click in Assets. Select Create > C# Script.

A new file will appear in Assets. Name the file “Cube”.

When you create or update a script, a wheel will spin in the bottom right corner of the Unity window. This wheel spins when a compilation occurs. A compilation takes lines of code and converts it to a format that is easier for your game to process.

When the compilation is complete, the script has been added or updated. Then you can run the game to see the changes the script applies.

Every time you change and save a script, Unity will re-compile the project to ensure that everything is correct. If there is a mistake in your code, such as a missing character or invalid variable name, a message will appear in the Console.

Currently, the Cube script will not execute any code because it is not attached to any object. Let’s attach the script to the Cube game object. Drag and drop the Cube script to the Cube game object in the Hierarchy or Scene. Alternatively, drag and drop the script to a blank space in the Cube object’s Inspector.

A Cube (Script) component will appear in Cube’s Inspector.

Double-click on the Cube script in Assets to open it. The file “Cube.cs” will open in MonoDevelop-Unity, as evident in the next image. MonoDevelop is a free, open-source coding interface that downloads when you download Unity if you do not unselect Unity’s default downloads.

Note that if you prefer to use other tools, such as Visual Studio, Sublime Text, or Notepad++, you can configure Unity to use that text editor by default.

The first line in the script is using UnityEngine;. This line means that the code in the script can use items already implemented in the Unity engine.

using System.Collections; means that the script can use certain parts of the code that are already written in the C# environment for collecting objects.

The other code in the file defines the Cube class. public class Cube defines a public class called Cube. : MonoBehaviour means the class extends MonoBehaviour, which is the base class for a game object. The code we write between the curly braces will change how Cube behaves.

The default methods in the Cube class are Start and Update. The Start method executes code when the game begins. The Update method executes code constantly. Want to learn more about methods? Check out our Unity3D course, where you build 30 virtual reality games! Don’t forget to save your project.