C# for Unity — Lesson #1: Data Types and Variables

February 25 2021

C#programmingUnityvirtual reality

What are Data Types

Computers work by manipulating pieces of data, like adding numbers or concatenating strings, for example. A data type defines the operations that can be done on the data, the meaning of the data, and how much space this piece of data needs to be stored on the memory. Without them, programs could end up trying to multiply a text, for example.

Data types can also help the programmer write the code. When all data types are explicitly defined in a script, understanding the code becomes much easier. It also works as built-in documentation. In C#, you are required to specify the type of everything, but that is not the case for every programming language.

Common Data Types

There are well over 10 data types in C#; luckily, we can get away with way less than that for game development in Unity. The built-in data types that you must know are:

int // Whole Numbers, eg: 42, -13, 1337

float // Decimal Numbers, eg: 123.456f, -0.000666f

string // String of characters (Text), eg.: "Oculus", "Circuit Stream"

bool // Boolean values: true or false

When declaring texts, always remember to put them inside “double quotes”.
When declaring floats, always remember to add an ‘f’ at the end of the decimal number: 9.99f

Code Usage

Data types are used all across your code, and we will go over each of these usages, starting with variables!

Variables

During the execution of your code, we need a way to store data for future usage. It would be foolish to calculate a super complex formula just to forget it a moment later. Variables exist for this. Think of them as little boxes where data is kept for later usage.

But then, how big should that box be? Or in other words, what are we storing? That sounds like a problem for our buddies Data types!

Variables and Data Types are deeply intertwined; To declare a variable, you must always give it a name and a Data Type.

Usage

// Declares a variable named enemiesCount, of type int

int enemiesCount;

// declares a variable and automatically assigns "ArthurRibeiro" to it

string PlayerName = "ArthurRibeiro";

// Variables without assignment will be set to a default value

float velocity; // Defaults to 0.0f

velocity = 24.68f; // Assigns value to an existing variable

// Create a speed variable and assign the value currently stored in velocity.

float speed = velocity; // Sets to 24.68f

With a variable declared, we can use them throughout the program, much as we did on that last statement.

The actions performed by a program are expressed in statements, declaring a variable is an example of a statement. Every statement should end with a semicolon ( ; ).

The variable names must follow some rules, keep them to common Latin letters, and you will be fine.

The two forward slashes ( // ) in the snippets above are used to add a single-line comment to your code. Anything between the slashes and the end of the line will be completely ignored when executing the program. This is a great way to explain your code and make it more readable.

Converting Data Types

Often you will have to use a variable as it were from a different data type, that is called converting. Some examples are:

  1. Display a number in the UI (Text).
  2. Distribute a number of enemies (int) in space (float).
  3. Trying to read a value from a user input string.

Usage

int myInt = 2;

// Automatically converts and assigns myInt to myFloat
float myFloat = myInt;

// Unity console displays an error message!
myInt = myFloat;

C# will convert values automatically on some usages, referred to as "Implicit Conversion," but that only happens if no loss of data would incur. In our second conversion, we would lose the decimal values stored in a float, and so, the C# compiler raises the error:
Cannot implicitly convert type 'float' to 'int'. An explicit conversion exists (are you missing a cast?)

So, as the message tells us, there is an explicit conversion:

float myFloat = 3.7f; // Explicitly tells C# to convert the variable to int and only then assign it to myInt variable int myInt = (int)myFloat;

“(int)” is called a “cast operator” and is used to explicitly tell the compiler to convert that value to the casted data type.

Arithmetic Operators

Operators

Operators manipulate numeric variables and values to create new ones, just like common math would.

int myIntA = 12;

// Declares variable myIntB, and assigns the sum of myIntA(12) and 3, resulting in 15.

int myIntB = myIntA + 3;

// Sets the value of variable myIntA to the difference between myIntB(15) and myIntA(12), resulting in 3

myIntA = myIntB - myIntA;

// Declares variable myFloatC and assigns the multiplication of 1.5 and 3, resulting in 4.5f

float myFloatC = 1.5f * 3;

// Assigns to myFloatC the result from the division of 1.5 and 3, resulting in 0.5f;

myFloatC = 1.5f / 3;

Order of Operations

C# calculates the final value of the expressions using the order of operations, similar to how we do in common Math. So, multiplication and division are resolved before addition and subtraction.

// = 5 | Division comes before addition

int myIntA = 3 + 4 / 2;

// = 7.27f | Use parentheses to change the order the operators are resolved float myFloat = (3 - 2) * 7.27f;

// = -6 | Use parentheses to improve readability

float myFloat = 12 - (6 * 3);

Data Type Conversion

Now, are the results from these two lines equal?

float myFloatA = 5 / 4;

float myFloatB = 5 / 4.0f;

float myFloatC = 1f + 1 / 4;

The answer is NO!

In the first line we are dividing integer numbers, so the result is rounded to the nearest integer, making the assigned value = 1.

On the second line, since we have number 4 declared as a floating point number (4.0f), the operation is completed using float as the target data type, making the assigned value = 1.25f;

On the third line, even though we have the number 1 declared as a float, due to the order of Operations, first the program will resolve the division, which is between two integers, this leads to a loss of fraction just like the first line, making the final assigned value of the whole expression = 1f.

When using operators, it’s essential to pay attention to data types. C# combines the operations always using the data type with the most information.

Be careful with your data types 🙂

Advanced Math

Complex mathematical operations in Unity are done using a built-in class called Mathf.

In future posts we will go through what is a class and how to use them, but for now a small snippet of how it looks like:

float myFloatA = Mathf.Sqrt(9.0f); // Assigns 3.0f to myFloatB;

float myFloatB = Mathf.Abs(-3); // Assigns 3.0f to myFloatA;

Coming up next!

Next week we’ll take a look at Programming Logic and Conditionals. Now that we've got our bearings with what data types are, it’s time to dive into how the code statements are executed and how we can influence that!

Happy coding 🙂

🔙  Back to the Learn C# for Unity menu

WRITTEN BY

Arthur Ribeiro / Dejan Gajsek

Circuit Stream Instructor

Receive our newsletter to stay on top of the latest virtual reality and augmented reality info.