Activating Virtual Reality | Unity Tutorial

The first step to making a virtual reality (VR) game is activating VR Mode. In this tutorial, you will learn how to integrate a VR software development kit (SDK). If you are a beginner and want to learn how to build virtual reality games, check out our Unity3D course!

What is VR Mode?

Create a new Unity project named “VRInteractions”. Save the file to your Project folder. Leave 3D rendering enabled.

In the file that opens, select Main Camera from the Hierarchy. Notice that in the Scene window, there are gray lines protruding from the camera. These lines outline the area that the camera renders.

Create a cube in the Hierarchy. Put the cube in the position 0 0 0. Select Main Camera. In the Scene, you will be able to see that the cube is inside the rendering area of Main Camera. The cube is inside the shape made by the gray lines protruding from Main Camera.

If you move the cube outside the area outlined by the gray lines, the camera will not render the cube. The player will not be able to see the cube.

A VR game contains two cameras to represent two human eyes. The left camera shows the scene from the player’s left eye. The right camera shows the scene from their right eye. With the help of a VR device, dividing the view into two cameras makes feel as though they are in a virtual world.

Downloading SDK

Delete Cube and Main Camera (1) from the Hierarchy. There are multiple ways to create a VR environment. We will use the SDK of Google Cardboard. Google Cardboard is a VR platform in which a user places a smartphone into a cardboard viewer. When the user looks into the viewer, they see the game on their phone in 3D.

If you do not have Google Cardboard, you can change the SDK settings to disable VR Mode. You will be able to play the game on your phone without VR Mode.

To download Google Cardboard, go to www.developers.google.com/vr/unity. You will reach the page “Google VR SDK for Unity”. This page provides details about what the features of this SDK.

The bottom of the page contains useful links. Click on the “Unity API Reference” link to open a page containing details on how to implement the SDK.

You can look through this page to see details regarding the coding of the SDK, such as the available classes.

To download the SDK, click on the “Google VR SDK for Unity” link at the bottom of www.developers.google.com/vr/unity.

To integrate the SDK into the Unity project, you could clone the entire repository hosted on GitHub. Alternatively, click on the “gvr-unity-sdk” link.

You will be taken to a GitHub webpage. Click on “GoogleVRForUnity.unitypackage”. On the page that loads, press the Download button to download the SDK.

Double-click on the file that appears in your Downloads folder. Once the files decompress, an Import Unity Package window will open.

A Unity Package is like a zip file. It is a compressed file that contains many other files inside it.

You can see that the file contains scripts, materials, images, prefabs, and more. Instead of making our own plug-ins, we can import the ones in this package and adjust them. Press the Import button. Once the assets import, all the necessary files for activating the VR Mode will be in your Assets folder.

Depending on the Unity or SDK version you are using, you may be prompted to perform another import to ensure compatibility. You can press Import Package > Import to import the second package.

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

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!