Unity Tutorial for Beginners. C Sharp in Unity. Image from Ackosmic Games

4. Variables and Data Types

In this Unity Tutorial you will learn what "Variables" and "Constants" are, and the "Data Types" they can store (also, how to work with them within Unity and C#).

Unity Tutorial Level: Beginner.

4.1 Variables and Constants.

"Variables" and "Constants" can be defined as "computer memory sections reserved for storing data".

With "Variables", the "stored data" can be known or not, fixed or changing (variable).

With "Constants", the "stored data" is fixed, known and never changing (constant).

Being both "reserved memory sections", we can make use of them during the code execution (while the scene/game is running).

We use Variables and Constants to store information that is useful to develop our games (for example, the player score, if the game is over, a character name, and so on).

Note: In order to be used correctly. Variables and Constants need to have a "Unique Name" (otherwise we would not know which one to refer), and as we saw with "Scripts", Variables and Constants names have some rules:

  • Only use Alphanumeric characters (no symbols or spaces, because they can create conflict with other instructions).
  • Use lowercase and uppercase (use the "Camel Case" notation). Lower case at the beginning of the variable name or Constant and Capital case at the beginning of the second and subsequent words (example: playerScore, gameOver, enemyName).
  • Try to assign "names that describe" correctly the use we are going to give to the Variable or Constant (although they may seem extensive, it is always better to use "playerScore" instead of just "score").
  • Do not use as a names, system-specific functions (from Unity or C # libraries).
  • To know more about this topic, visit https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/capitalization-conventions .
"Ads" (the Ads Help us to Maintain this "Great Site" 😀 )

4.2 Data Types.

As we have already seen, Variables and Constants "store data", now we will see what Data Types they can store.

The most common Data Types are the next:

“int” Data Type.

We use this data type to store 32 bits "integer numbers" (in a range from -2,147,483,648  to  2,147,483,647).

Example:

If we want a "variable" that stores the "number of lives for our hero", we can do the next:

int heroNumberLives = 3;

 

If we want a "constant" that stores "the price of an armor", we can do the next:

const int armorPrice = 100;

Note: As you can see, in previous examples, to "declare a Variable" it is only necessary to write the "Data Type" that it will contain and the "Variable Name"; but for "Constants", it is necessary to write "const" before the "Data Type" and the "Constant Name".

 

“float” Data Type.

We use this data type to store 32 bits “floating point numbers” (in a range from -3.402823× 10^38   to   3.402823× 10^38).

Example:

If we want a "variable" that stores the "spaceship speed", we can do the next:

float spaceshipSpeed = 17.74f;

 

If we want a "constant" that stores the "planet's gravitational acceleration" value, we can do the next:

const float planetGravity = 4.978f;

Note: When we declare "float" types Variables or Constants; the value to be stored must include the suffix "f" (in order to differentiate it from  other Data Types for numerical values).

 

“string” Data Type.

This Data Type is used to store "character strings" in other words "text" (there is no official definition of how many characters can be stored, but we are sure that they will be enough for our purposes, or until the computer memory overflow, whichever comes first 😀 ).

Example:

If we want a "variable" that stores “a character name”, we can do the next:

string characterName = “Ronnie the Fox”;

 

If we want a "constant" that stores a “welcome message”, we an do the next:

const string welcomeMessage = “Welcome to ACKOSMIC Games”;

Note: When we declare "string" types Variables or Constants; the text to be stored must be typed “between double quotes” (“ “).

 

“bool” Data Type.

We use this Data Type to store the logical (Boolean) values ​​"true" or "false"; it does not support other values and it is not necessary to write them between double quotes.

Example:

If we want a "variable" that stores if “the game is over” (or not), we can do the next:

bool gameOver = false;

Note: It is not common to use “bool” types for Constants.

 

There are many others Data Types, but these four ("int", "float", "string" and "bool") are the ones we will use most often when we start to develop video games; later in next tutorials we will see how to declare other Data Types for variables and constants.

If you want to know more about C# Data Types, visit https://docs.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/types-and-variables .

"Ads" (the Ads Help us to Maintain this "Great Site" 😀 )

4.3 Working with Variables.

Now, we will see how to work with Variables Constants within Unity and C#.

In Unity, let's create a new Script called “MyVariables” (in the “Project” window, “right click” over the “Scripts” folder and choose Create → C# Script). Another way to create a Script is, by selecting the “Scripts” folder and from the Menu Bar go to Assets → Create → C# Script.

Unity Tutorial. C Sharp (C#). Unity Editor Interface Image from Ackosmic Games

 

Once the file “MyVariables.cs” is created, “double click” over it to open the code editor (or try a “right click” over the script and choose “Open C# Project”.

 

Unity Tutorial. C Sharp (C#). Unity Editor Interface Image from Ackosmic Games

With "MyVariables" open in the code editor, let's create the “First Variable” and the “First Constant” in order to show them as part of some messages in the "Unity's Console".

Within the “MyVariables” Class but before the “Start” and “Update” Methods, let's "create" (or "declare") the next Variable and Constant:

//The Player's health amount. With a initial value of "100" units.
int playerHealth = 100;
//The Damage amount that the Player can receive.
const int playerReceivedDamage = 10;

Note: The text that is after the "double slash" ( // ) is called "Comments", and it helps us to leave notes within our code, annotations that help as a reference to know with a little more detail what we are doing. The comments are not taken into account when compiling and executing our code; what is after the two diagonals and on the same row is considered as Comments (then, we will see another way to write comments that use more than one row).

Now, inside the “Satrt” Method, let's type:

Debug.Log("Initial Health: " + playerHealth);
Debug.Log("Received Damage: " + playerReceivedDamage);

Debug.Log” helps us to display messages in the Unity's Console, these messages must be in "Text" format (between "double quotes"); in the case of variables and constants, we do not put them in double quotes because what we want to know is the value they store (otherwise in the Unity's Console we would see only the "Variable or Constant name" and not its value).

The “plus” (+) symbol between the showing text and the variable or constant is used to indicate that we are "adding" (concatenating) more information to display.

All the coding must look like this:

Unity Tutorial. C Sharp (C#). Unity Visual Studio Code Image from Ackosmic Games

 

 

Let's "Save" the Script ( Ctrl+S ).

Now switch to the Unity Editor Interface (remember to wait a bit while Unity takes the changes made in the code editor).

In the “Hierarchy” window, select the game object named “GameObject”, once is selected, look at the “Inspector” window and remove the  “Hello World (Script)” “Component”(remove the “HelloWorld” Class Instance). To remove it, click over the “small cog” at the component's upper right corner (each game object's component has one) and choose “Remove Component” from the displayed menu.

Unity Tutorial. C Sharp (C#). Unity Editor Interface Image from Ackosmic Games

With this the component “Hello World (Script)” will be removed (and cannot be executed when running the scene).

"Ads" (the Ads Help us to Maintain this "Great Site" 😀 )

The next step is to add the “MyVariables”script as "Component" to this same game object  (just click on the “Add Component”, then from the displayed menu choose “Scripts” and select “My Variables”).

Once the “My Variables” Component  is assigned (the “MyVariables” Class Instance), is time to click on the “Play Button” of the Unity Editor Interface to run the scene (while running the scene, the “Play Button” will be activated, and its color will change from “Black” to “Blue” color, keeping in Blue until the scene is stopped).

Unity Tutorial. C Sharp (C#). Unity Editor Interface Image from Ackosmic Games

The Unity's Console will show:

Unity Tutorial. C Sharp (C#). Unity Editor Interface Image from Ackosmic Games

 

 

Let's click on the “Play Button” again in order to stop the scene (the “Play Button” will change its color back to “Black” 😀 ).

Now, go back to our code editor to add more variables and constants. After the constant “playerReceivedDamage” let's type:

//The Player velocity in km/h.
float playerVelocity = 14.74f;
/* The Planet's Gravitational Acceleration in m/s^2. 
This Value has to be set as "Constant" */
const float planetGravity = 7.44f;

Note: When using “Comments” that requieres more than one row; use the symbols “ /* ” and  “ */ ” tu write the comments between them.

Inside the “Start” Method, let's type:

Debug.Log("Player's Velocity: " + playerVelocity + " km/h");
Debug.Log("Planet's Gravitational Acceleration: " + planetGravity + " m/s^2");

Note: Use the “+” symbol when to add more information for the message is required (from this example: "text" + variableValue  + "more text").

The Script will look like this:

Unity Tutorial. C Sharp (C#). Unity Visual Studio Code Image from Ackosmic Games

 

 

Save the Script ( Ctrl+S ).

Switch to the Unity Editor Interface (remember to wait a bit while Unity takes the changes made in the code editor) and Run the Scene.

The Unity's Console will show:

Unity Tutorial. C Sharp (C#). Unity Editor Interface Image from Ackosmic Games

 

 

Stop the scene. Now switch back to the code editor to add the following Variables and Constants. After “planetGravity” let's type:

//A Welcome Message to the Player
string welcomeMessage = "Welcome to this Great Game. ";
//A Message to Start the Game
const string gameStartMessage = "Please, Click to Start";
//A Reference or "Flag" to know if the Game has Started
bool isGameStarted = true;

Inside the “Start” Method, type:

Debug.Log(welcomeMessage + gameStartMessage);
Debug.Log("Game Started: " + isGameStarted);

The Script will look like this:

Unity Tutorial. C Sharp (C#). Unity Visual Studio Code Image from Ackosmic Games

 

 

 

Save the Script ( Ctrl+S ).

Switch to the Unity Editor Interface (remember to wait a bit while Unity takes the changes made in the code editor) and Run the Scene.

The Unity's Console will show:

Unity Tutorial. C Sharp (C#). Unity Editor Interface Image from Ackosmic Games

 

 

Stop the scene.

Before finalizing, save all your work (go to File → Save Scenes and then File → Save Project).

"Ads" (the Ads Help us to Maintain this "Great Site" 😀 )

Exercises.

For getting a stronger knowledge about what you have already learned, it is necessary to practice it, so try to perform the following exercises:

  1. Use the “MyName” Script create in the past exercise.
  2. Add the following Variables and Constants:
    • int” type Variable for your age.
    • int” type Constant with your zip code.
    • float” type Variable for your height.
    • float” type Constant for your weight.
    • string” type Variable for your adress.
    • string” type Constant for your hobbies.
  3. Inside the “Start” Method, after the past code (do not erase it), and using the Variables and Constants you've already created, write a new code that show a Message in the Unity'Console describing yourself.
  4. Use the existing game object, replace the component used in this tutorial (“My Variables”) by an instance of your Script (“My Name”).
  5. Run the scene and look the result.

This Unity Tutorial about  “Variables”, “Constants”, “Data Types” and how to work with them in a “Script” end here. Join us in the next post where we will continue learning more about programming in C Sharp (C#) Language.

Remember, if you want to know more about this topic, you can always visit Unity's online user manual at https://docs.unity3d.com/Manual/ or, do not hesitate to contact us for any questions or advice by clicking “Here”.

Next Unity Tutorial: 6. Conditionals

"Ads"
Share this Post
Posted in CSharpAndUnity.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.