C# Programming In Unity – Introduction To Variables

Table of Contents

C# Programming In Unity – Introduction To Variables

Reading Time: 7 minutes
Level: Beginner
Version: 2020.3.1 LTS

Help Others Learn Game Development

Variables are the foundation of programming. To represent anything in your game, be that player’s name, health status, how much ammo you have left and so on, you need variables.

As you can see from the few examples I mentioned what we can represent with variables, you already know that these variables are numbers and characters.

Creating Our First Script

Before we start to write any code, let us create our first script. In the project tab Right Click -> Create -> C# Script:

Image 1 - 60%

As soon as you create a new script in Unity, you will be prompted to give it a name. Give this script a name: LearningHowToProgram

The name itself is not important for our lectures that will come in these posts, but later when you start creating your game you will give meaningful names for your scripts.

These names represent the task for which you want to use the script such as PlayerMovement, PlayerAnimation, EnemAI and so on.

Double click the script and this will open it in Visual Studio:

Image 2 - 60%

We are not going to go through every part of the script to explain what everything represents, but what’s important for us at the moment to understand is that the Start function that you see is used for initialization of your script.

For example, if you want to calculate some values before your game starts, then you would do that in the Start function. Later down the road we will discuss the initialization functions in more depth, because there are in total 3 functions that serve this purpose.

The reason why I mentioned Start now is because any code that we want to print to the console as an example, we will type it in the start function. Now we can jump into the juicy parts and finally introduce variables.

Decimal Point Variables

As we already mentioned variables are numbers and characters, but there are multiple types of variables that we can use, such as whole numbers or decimal point numbers. So the first variable that I will introduce to you is called a float:

				
					float heath = 100f;
				
			

Type this line of code above the Start function so that you have something like this:

				
					 float health = 100f;

    void Start()
    {
        
    }
				
			

All variables that we want to use inside the specific script we will declare above the Start function or to be more precise right below the public class declaration.

We will see more examples of that, but now let’s talk about the structure of declaring a variable and break down the line of code that we wrote.

When declaring a variable, we first give it a type, then we give it a name, and optionally we give it a value, same as what we did with the float example:

Image 4 - 0%

The variable type and name are mandatory when you want to declare a variable of any type, but the value is optional which means that you don’t have to give your variable a value right away, you can calculate it later during gameplay.

The variable that we declared in this example is called a float, and it represents a decimal point number.

Now you will notice that the number we gave our float as its value is 100, it’s not 100.0 which represents a decimal point number, and the reason for that is when you have 0 after the decimal point you can omit it and still the number will count as a decimal point number in the code.

The compiler will add .0 at the end of that number when it’s ready to use it and you don’t have to do any extra work. If we were to declare 100.5 then we would have to specifically add .5 at the end of the number.

The “f” suffix at the end of the declaration is used to denote that this number is a float type number. This is because we have another variable type that also represents decimal point numbers which is called a double, and this is how we declare it:

				
					double power = 100;
				
			
Again, you will notice the same signature, we first declare the variable type, then the name then we give it a value.
 

In this example you see that we gave our double a value of 100, but we didn’t add f at the end. The compiler automatically knows that this number is a double because we specified that with the variable type, and we don’t need to add f at the end. 

Same as with the float, you can omit the .0 at the end, but if you have any other value other than 0 as a decimal point number then you must type it.

Now the question arises, what is the difference between a float and a double? Because both variables represent decimal point values, so what is the difference, if any.

From all the research that I did, I came to the conclusion that the main difference between the two variables is that the double is more precise when it comes to the decimal point numbers.

To give a rough example, a float can be 100% precise up to the 15th decimal number e.g. 2.435353535353535 and a double can be 100% precise up to the 25th decimal point number e.g. 2.4353535353535353535353535.

These examples are rough examples as I already mentioned, or better yet, this is me trying to use human language to explain the difference between the two variables as best as I can, but for the majority of our development we will use floats to represent decimal point numbers in our projects.

I’ve been using Unity for 7 years and not once have I used a double to represent a decimal point number.

Whole Number Variables

Moving forward, the same way how we have decimal point numbers, we also have whole numbers and they are called integers. This is how we declare an integer variable:

				
					int speed = 10;
				
			

int is short for integer, and that represents the variable type, then we give it a name and after that the optional value. Integers don’t have any letters that you can add at the end of the variable declaration so we just give it a value we want and that’s it.

Character Variables

Next we have a string variable which is a character type variable, and this is how we declare it:

				
					string playerName = "Knight";
				
			

string is the type of variable, so we declare it first, same as with the other variable types, then we give it a name and an optional value.

One thing to note is that whenever you want to type a string value, you do that in quotes, so any value that you want to type needs to be in between the “” marks.

It’s important to know that anything you type between the quote marks will be counted as a string variable, so if you type space, this counts as a character, which means that

				
					string playerName = "Carl Johnson";
				
			

is not the same variable as

				
					string playerName = "CarlJohnson";
				
			

so keep that in mind.

Boolean Variables

The last variable that we have is called a boolean, and this a variable that can only have true or false as its values. This is how we declare it:

				
					bool isAlive = true;
				
			

bool is the type of the variable, isAlive is the name and true is the value. We can also type false instead of true, but these are the only two values that the boolean variable can have.

This is because booleans are used in conditional statements that can only be true or false, and we will see many examples of this.

Naming Conventions For Variables

Another thing to note is when using C# and Unity you will use a camel case way of writing variable names, such as isAlive.

The name of the variable starts with a lower case letter then every beginning letter of every new word in the variable name is capitalized such as Alive in this case.

The are also other naming conventions that you can follow such as using underscores and giving your variable a name like this:

				
					bool _isAlive = true;
				
			

Or even

				
					bool is_Alive = true;
				
			

We will use both of these examples in our development so you will get used to it.

Conclusion

After you declared all of these variables this is how your script should look like:

				
					float health = 100f;

    double power = 100;

    int speed = 10;

    string playerName = "Knight";

    bool isAlive = true;

    void Start()
    {
        
    }
				
			

This would be it when it comes to variable types that we can use to develop our games and these 5 types of variables are the foundation of any game that you will create.

From now on we will use all of these variable types A LOT in our development so you will become a master variable manipulator 🙂

One Last Tip - Comments

You probably noticed the words above the Update and Start functions when you created your script:

				
					 // Start is called before the first frame update
    void Start()
    {
        
    }

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

These are called comments and they are not counted as lines of code.

This means that you can write anything you want in the comment and they are primarily used to document code.

You create comments by typing // and after that you can add notes that will help you understand what your code is about when you come back to it after a few months.

One thing to note is that don’t overdo the comments and write paragraphs about what your code does, instead use few words that describe what your code is doing. For example:

				
					// players movement
// detecting enemy presence
// dealing damage
				
			

And so on.

Where To Go From Here

In this lecture you learned about the most essential part of every game that we will create – variables.

To continue your learning journey you can take a look at our Math Operations With Variables Lecture which is the next lecture in this tutorial series.

122 thoughts on “C# Programming In Unity – Introduction To Variables”

  1. ดาวน์โหลดแอป w69 – https://rebe0.com ได้ง่ายๆ เพียงไม่กี่ขั้นตอน พร้อมรับโบนัสต้อนรับ 100$ สนุกกับการเดิมพันที่ดีที่สุดบนมือถือ

    Reply
  2. Tham gia ibet888 – https://ibet888-vn.com ngay hôm nay để nhận thưởng 100$ khi gửi tiền lần đầu. Đăng ký tài khoản nhanh chóng chỉ trong 3 phút: truy cập trang web, nhấn “Đăng ký”, điền thông tin và xác nhận. Sau đó, bạn có thể đăng nhập và bắt đầu hành trình cá cược đỉnh cao với nhiều phần thưởng hấp dẫn.

    Reply
  3. ดาวน์โหลดแอป w69 betวันนี้
    รับโปรโมชั่นพิเศษมากมาย ใช้งานสะดวก ปลอดภัย และรองรับทุกอุปกรณ์

    Reply
  4. bk7 – https://qtb29.com ปรับปรุงอินเทอร์เฟซแอปให้ใช้งานง่ายขึ้น ดีไซน์สวยงาม ค้นหาเกมได้รวดเร็วและสะดวกสบาย

    Reply
  5. วิธีติดตั้งแอป w69 asia
    https://ktrg0.com บนมือถือ ใช้เวลาเพียงไม่กี่นาที รองรับทุกระบบ ให้คุณเริ่มเดิมพันได้ทันที

    Reply
  6. Sign up for luxebet and
    get a $100 bonus right away! As a new user, this exclusive offer is your chance to
    start playing with extra funds. Explore a wide range of
    online casino games, from slots to poker and blackjack.
    Your $100 bonus will help you make the most of your gaming experience.
    Don’t wait—register today and claim your bonus!

    Reply
  7. วิธีติดตั้งแอป w69 com บนมือถือ
    ใช้เวลาเพียงไม่กี่นาที รองรับทุกระบบ ให้คุณเริ่มเดิมพันได้ทันที

    Reply
  8. winny welcomes new players with a fantastic $100 bonus!
    Register now and get this bonus to start your journey through
    a diverse selection of online casino games, slots, poker, and sports betting.
    Take advantage of this exclusive offer—sign up today and enjoy a premium
    gaming experience with your $100 bonus!

    Reply
  9. Get started on betfury
    today and enjoy a $100 bonus upon registration! Signing up is quick and simple.
    Just create an account, log in, and you’ll be instantly rewarded with a
    $100 bonus. This welcome offer is exclusive to new users, providing a fantastic opportunity to
    boost your gaming experience right from the start. Don’t
    miss out on this limited-time offer. Register
    today, and the bonus will be yours as soon as you complete your sign-up process.

    Reply
  10. Looking to join unibet?
    Sign up now and claim your $100 bonus! The process is easy and quick, allowing you
    to register, log in, and get your bonus within minutes.
    With the $100 bonus, you can explore a wide range of casino games.

    Don’t miss out on this special offer for new users. Register now and start playing with extra funds!

    Reply
  11. Looking for a way to boost your online casino experience?
    nextbet has just the solution! Register as a new user and claim a $100 bonus to start playing
    right away. Whether you’re into sports betting or exploring the
    latest slots, this bonus gives you the perfect opportunity to get familiar with the platform and
    its offerings. Don’t miss out—sign up today and
    start playing with your $100 bonus in hand!

    Reply
  12. Get started on ivibet today and enjoy a $100 bonus
    upon registration! Signing up is quick and simple.
    Just create an account, log in, and you’ll be instantly rewarded with a $100 bonus.

    This welcome offer is exclusive to new users, providing a fantastic opportunity to boost your gaming experience
    right from the start. Don’t miss out on this limited-time offer.

    Register today, and the bonus will be yours as soon as you
    complete your sign-up process.

    Reply
  13. Looking for a great start on betshah?

    New users get a $100 bonus when they register!
    The registration process is quick and easy. Just fill in your details, log in, and your
    bonus will be waiting for you. With your $100 bonus, you’ll
    be ready to explore the exciting world of online
    casinos, from classic slots to live dealer games.

    Sign up now and take advantage of this amazing offer!

    Reply
  14. Ready to win big at puma?
    New users can claim a $100 bonus upon registration, giving you
    the perfect opportunity to explore a variety of exciting games, from slots to
    live casino tables. Don’t miss out on this exclusive offer—sign up today and
    claim your $100 bonus to get started on your winning journey!

    Reply
  15. Sign up on casitsu and
    enjoy a $100 bonus right after registration. It’s simple
    to register: just fill in your details, log in, and the bonus will be yours.

    Whether you’re new to online casinos or an experienced player, the $100 bonus will enhance your experience and give you more
    chances to win. Don’t miss out on this special offer – register now
    and claim your bonus today!

    Reply
  16. Aproveite a oferta exclusiva do luck 2
    para novos usuários e receba 100$ de bônus ao se registrar!

    Este bônus de boas-vindas permite que você experimente uma vasta gama de jogos
    de cassino online sem precisar gastar imediatamente.
    Com o bônus de 100$, você poderá explorar jogos como roleta, blackjack, caça-níqueis e muito mais, aumentando suas chances de vitória desde o primeiro minuto.
    Não perca essa chance única de começar com um valor significativo – cadastre-se agora!

    Reply
  17. No b1bet, novos usuários
    podem aproveitar um bônus de 100$ ao se registrar no site!
    Isso significa mais chances de ganhar e explorar uma grande
    variedade de jogos de cassino, desde slots emocionantes até clássicos como roleta e blackjack.

    Com o bônus de boas-vindas, você começa com um saldo extra, o que aumenta suas chances de sucesso.
    Cadastre-se agora e use os 100$ de bônus para experimentar
    seus jogos favoritos com mais facilidade. Aproveite a
    oferta e comece sua aventura no cassino agora mesmo!

    Reply
  18. No winbra,
    novos usuários podem aproveitar um bônus de 100$ ao se registrar no site!
    Isso significa mais chances de ganhar e explorar uma grande variedade de jogos
    de cassino, desde slots emocionantes até clássicos como roleta
    e blackjack. Com o bônus de boas-vindas, você começa com um saldo extra,
    o que aumenta suas chances de sucesso. Cadastre-se agora e use os 100$ de bônus para experimentar seus jogos favoritos com mais facilidade.
    Aproveite a oferta e comece sua aventura no cassino agora mesmo!

    Reply
  19. I’m curious to find out what blog system you have been utilizing? I’m experiencing some minor security issues with my latest blog and I would like to find something more secure. Do you have any recommendations?

    Reply
  20. O jogodeouro oferece uma
    excelente oportunidade para quem deseja começar sua experiência
    no cassino online com um bônus de 100$ para novos jogadores!
    Ao se registrar no site, você garante esse bônus
    exclusivo que pode ser utilizado em diversos
    jogos de cassino, como slots, roleta e poker.
    Esse é o momento perfeito para explorar o mundo das apostas com um saldo extra, aproveitando ao máximo
    suas apostas sem precisar investir um grande valor logo
    de início. Não perca essa oportunidade e cadastre-se já!

    Reply
  21. After checking out a handful of the blog articles on your blog, I really appreciate your way of writing a blog. I book marked it to my bookmark website list and will be checking back soon. Take a look at my web site as well and let me know your opinion.

    Reply
  22. Hi! I’ve been reading your blog for a while now and finally got the bravery to go ahead and give you a shout out from Humble Texas! Just wanted to mention keep up the great job!

    Reply
  23. No misterjackbet, novos usuários podem
    aproveitar um bônus de 100$ ao se registrar no site! Isso significa mais chances de ganhar e
    explorar uma grande variedade de jogos de cassino, desde slots emocionantes até
    clássicos como roleta e blackjack. Com o bônus de boas-vindas,
    você começa com um saldo extra, o que aumenta suas chances de sucesso.

    Cadastre-se agora e use os 100$ de bônus para experimentar seus jogos favoritos com mais facilidade.
    Aproveite a oferta e comece sua aventura no cassino agora mesmo!

    Reply
  24. O aposte e ganhe oferece uma excelente oportunidade
    para quem deseja começar sua experiência no cassino online com
    um bônus de 100$ para novos jogadores! Ao se registrar no site,
    você garante esse bônus exclusivo que pode ser utilizado
    em diversos jogos de cassino, como slots, roleta e poker.
    Esse é o momento perfeito para explorar o mundo das apostas com um saldo extra, aproveitando ao máximo suas apostas sem precisar
    investir um grande valor logo de início.
    Não perca essa oportunidade e cadastre-se já!

    Reply
  25. Your style is unique in comparison to other folks I have read stuff from. I appreciate you for posting when you’ve got the opportunity, Guess I’ll just book mark this page.

    Reply
  26. Aproveite a oferta exclusiva do brwin para novos
    usuários e receba 100$ de bônus ao se registrar!
    Este bônus de boas-vindas permite que você experimente uma vasta gama
    de jogos de cassino online sem precisar gastar imediatamente.
    Com o bônus de 100$, você poderá explorar jogos como roleta,
    blackjack, caça-níqueis e muito mais, aumentando suas chances de vitória desde
    o primeiro minuto. Não perca essa chance única de começar com um valor significativo – cadastre-se
    agora!

    Reply
  27. Aproveite a oferta exclusiva do pinup bet
    para novos usuários e receba 100$ de bônus ao se registrar!
    Este bônus de boas-vindas permite que você experimente uma vasta gama de jogos de cassino
    online sem precisar gastar imediatamente. Com o bônus de 100$,
    você poderá explorar jogos como roleta, blackjack,
    caça-níqueis e muito mais, aumentando suas chances de vitória desde o primeiro minuto.
    Não perca essa chance única de começar com um valor significativo – cadastre-se agora!

    Reply
  28. Aproveite a oferta exclusiva do blaze para novos usuários
    e receba 100$ de bônus ao se registrar! Este bônus de boas-vindas permite que você experimente uma vasta gama de jogos
    de cassino online sem precisar gastar imediatamente.

    Com o bônus de 100$, você poderá explorar jogos como roleta,
    blackjack, caça-níqueis e muito mais, aumentando suas chances de vitória
    desde o primeiro minuto. Não perca essa chance única de começar com um
    valor significativo – cadastre-se agora!

    Reply
  29. No onebra, novos usuários podem aproveitar um bônus de 100$ ao se registrar no site!
    Isso significa mais chances de ganhar e explorar uma grande variedade
    de jogos de cassino, desde slots emocionantes até clássicos como roleta e blackjack.
    Com o bônus de boas-vindas, você começa com um saldo extra,
    o que aumenta suas chances de sucesso. Cadastre-se agora e use os 100$ de bônus para experimentar seus jogos
    favoritos com mais facilidade. Aproveite a oferta
    e comece sua aventura no cassino agora mesmo!

    Reply
  30. Ao se cadastrar no jogos win,
    você ganha um bônus de 100$ para começar sua jornada no cassino
    com o pé direito! Não importa se você é um novato ou um apostador experiente, o bônus de boas-vindas é a oportunidade perfeita para explorar
    todas as opções que o site tem a oferecer. Jogue seus jogos favoritos, descubra novas opções de apostas e aproveite para testar estratégias sem risco,
    já que o bônus ajuda a aumentar suas chances de ganhar.
    Cadastre-se hoje e comece com 100$!

    Reply
  31. No jonbet, novos usuários podem aproveitar
    um bônus de 100$ ao se registrar no site! Isso significa mais chances de ganhar e explorar uma grande variedade de jogos de cassino, desde slots emocionantes até clássicos como
    roleta e blackjack. Com o bônus de boas-vindas, você começa com um saldo extra,
    o que aumenta suas chances de sucesso. Cadastre-se agora e use os 100$ de
    bônus para experimentar seus jogos favoritos com mais facilidade.
    Aproveite a oferta e comece sua aventura no cassino agora mesmo!

    Reply
  32. Ao se cadastrar no 667bet,
    você ganha um bônus de 100$ para começar sua jornada no cassino
    com o pé direito! Não importa se você é um novato ou um apostador experiente, o bônus de boas-vindas é a
    oportunidade perfeita para explorar todas as opções que
    o site tem a oferecer. Jogue seus jogos favoritos, descubra novas
    opções de apostas e aproveite para testar estratégias sem risco, já que
    o bônus ajuda a aumentar suas chances de ganhar.
    Cadastre-se hoje e comece com 100$!

    Reply

Leave a Comment