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.

Build watchOS Apps for the Apple Watch | Course Release

Start now.

Do you want to build your own apps for the Apple Watch? Even if you have never coded before, you can build a watchOS app with our brand-new Apple Watch course.

You do not need any prior knowledge to take this course – it is perfect for beginners. The Apple Watch course begins by covering the fundamentals of the Swift programming language. You will learn how to use Xcode to create the layout and functionality of an iOS app.

If you do have experience developing for iOS, the Apple Watch course is your head start in developing for watchOS. You will learn the differences between coding for iOS and watchOS.

To learn how to develop for watchOS, we will create an Apple Watch app of our own in Xcode – from scratch. You will learn how to:

  • Add a basic label to create the layout of your app
  • Add and implement dates and timers
  • Insert switches, sliders, and pickers
  • Create different tables and context menus
  • Insert images and movies into your Apple Watch apps
  • Enable notifications

By the end of the Apple Watch course, you will have a functioning app that you can expand on to add your own ideas. You will be able to test the app like a user would. Let’s go!

Learn JavaScript in 1 Hour! Book Release

All you need is 1 Hour.

Do you want to learn the foundations of computer programming? Are you tired of being bogged down by confusing jargon and complex descriptions? We have the book for you: Learn JavaScript in 1 Hour.

Learn JavaScript in 1 Hour is an easy-to-understand introduction to JavaScript. With this book, your website will be up-and-running in no time!

Important topics in web development are shown with examples that are easy to read. If you have a Mac computer, PC, or even a mobile device, you can follow along with the book’s examples on www.jsbin.com. JSBin is an editor that allows you to see your creations in real time.

Learn JavaScript in 1 Hour covers topics including:

Functions – Finally your website can do things! It’s not just a pretty face. Learn how to enable your site to perform tasks.

Variables – Integers, doubles, floats, characters, strings: these are all different types of variables. Variables are crucial to programming because they contain data. Learn about the different types and when you should use each one.

If Statements – If you read Learn JavaScript in 1 Hour, you will reach the section on conditionals. If statements run code IF a specific condition is met. With an if statement, you can test a value, run certain code only when you want to, and prevent your site from crashing!

If you want to learn how to give a website functionality, Learn JavaScript in 1 Hour can teach you the foundations of using JavaScript. Even if you have never coded before, you can follow along. For more books on tech topics, visit our Lulu shop.

Making a Cube | Unity Tutorial

To prototype a game in Unity, you can design a scene using primitives. To learn how to build 30 virtual reality games in Unity, check out our Unity 3D course! There are a number of primitives, or elements, that you can create in Unity, such as a cube.

Later, you can create more complex 3D elements in modeling programs, such as Blender. Then you can import the art into Unity.

Creating a 3D Primitive

To make a 3D element, right-click in the Hierarchy. A menu will appear containing listing game objects you can create. Clicking “Create Empty” would create a net game object, which has only a Transform component.

In the “3D Object” tab, there are names of three-dimensional shapes. Click on “Cube”, as in the next image.

“Cube” will appear in the Hierarchy. A cube will appear in the Scene, as you can see in the following image.

Cube’s Components

In the Inspector, there are many components for Cube. To position the cube in the center of the scene, change the X, Y, and Z Position values to 0.

If you change Cube’s X Scale value, Cube’s size will change in the X axis. Changing the Scale’s Y value makes the cube taller or shorter. The Z Scale value corresponds to the cube’s size in the depth axis, as evident in the following screenshot.

To change Cube’s scale visually, click on the fourth icon in the top left of Unity. Colored cubes will extend from Cube’s center. You can drag the cubes to change Cube’s size. If you click and drag the gray cube in the center of the cube object, Cube’s size will change in all three axes at once.

The Cube (Mesh Filter) component is the data for the 3D object that is rendered on the Scene. The Box Collider is used to process collisions.

The Mesh Renderer draws the cube. If you disable the Mesh Renderer by un-checking it, the cube will become invisible.

To learn more about the Mesh Renderer and Unity, check out our Unity 3D course, where you build 30 virtual reality games!