Jump to content
  • Advertisement
  • 12/03/18 05:07 AM

    Unity Scripting: Working with Variables

    Engines and Middleware

    • Posted By Packt

    What is a variable? Technically, it's a tiny section of your computer's memory that will hold any information that you put there. While a game is running, it keeps track of where the information is stored, the value kept there, and the type of that value. However, for this chapter, all you need to know is how a variable works. It's very simple.

    This tutorial has been taken from Learning C# 7 By Developing Games with Unity 2017 - Third Edition and published by Packt.

    What's usually in a mailbox, besides air? Well usually there's nothing, but occasionally there is something in it. Sometimes, there are letters, bills, a spider, and so on. The point is that what is in a mailbox can vary. Therefore, let's call each mailbox a variable.

    In the game development world, some simple examples of variables might be:

    • playerName
    • playerScore
    • highestScore

    How to name a variable

    Using the example of the mailbox, if I asked you to see what is in the mailbox, the first thing you'd ask is, "Which one?" If I say in the Smith mailbox, the brown mailbox, or the round mailbox, you'll know exactly which mailbox to open to retrieve what is inside it. Similarly, in scripts you have to give your variables a unique name. Then I can ask you what's in the variable named myNumber, or whatever cool name you might use.

    Let's see how this is represented in our code. The first thing we need to do is create a new script in Unity, all the fun and magic starts here from these first steps:

    1. In the Unity project panel, under the Assets tab, we are going to right–click the empty space:


    1. Then we go to the Create menu and select the C# Script option

    2. A new file was created and it is ready to be renamed; this is very important and we need to always give a name to this file. For now, we can call it variableScript (the name we gave to this file doesn't interfere with the content on it, so we can we choose any name we want):





    1. Then we double-click the script file that we have just created.

    2. The MonoDevelop program will open with the script ready to edit:



    1. Make sure that the name that appears after public class is exactly the same name that you assigned inside Unity (in this example, we gave the name variableScript). In case we don't rename the script file right away when it gets created, Unity will automatically assign the NewBehaviourScript name:



    1. Now we are ready to create our first variable, we are going to name it myNumber. Make sure that your script looks identical to the following screenshot (for now, don't be concerned about the details of how to write this):



    1. Then save the file

    Note: When you name variables, try to come up with a name that most accurately describes what value your variable contains. Avoid generic names such as name, speed, and score. Instead, name them playerName, carSpeed, and opponentScore, respectively.

    A variable name is just a substitute for a value

    As you write a script and create a variable, you are simply creating a placeholder or a substitute for the actual information that you want to use. Look at the following simple math equation: 2 + 9 = 11.

    Simple enough! Now try the following equation: 11 + myNumber = ???. There is no answer to this. You can't add a number and a word. Going back to the mailbox analogy, write the number 9 on a piece of paper. Put it in the mailbox named myNumber. Now you can solve the equation. What's the value in myNumber? The value is 9. So now the equation looks normal: 11 + 9 = 20.

    The myNumber variable is nothing more than a named placeholder that can store some data (information). So, wherever you would like the number 9 to appear in your script, just write myNumber and the number 9 will be substituted.

    We can test this on the script that we had previously created, so let's do it:

    1. We start by selecting the script that we have created and then we double–click it to open inside MonoDevelop:



    1. Now we create a new variable called total and we don't need to assign any number to it because we want this variable to show us the result of our:


    1. After the void Start () function, we are going to write the math equation total = 2 + myNumber:



    1. Save the file, go back to the Unity program, and drag and drop the script file on top of the Main Cameraobject:


    1. Click Play and take a look at the Total variable:



    Although this example might seem silly at first, variables can store all kinds of data that is much more complex than a simple number. This is just a simple example that shows you how a variable works. We will definitely look at more complex variable types at later stages. Remember, slow, steady progress, baby steps!

    Creating a variable and seeing how it works

    Now using a different method, we are going to develop a script that shows us the result on the Unity console. Once again, don't be concerned about the details of how to write this; we are going to explain everything in more detail in future chapters. Just make sure that your script is the same as the script shown in the next screenshot:

    1. In the Unity Project panel, double-click variableScript. The MonoDevelop window should open automatically on variableScript.cs.

    2. In MonoDevelop, erase what we have done before and write the lines 7, 12, and 14, as shown in the following screenshot:



    1. Save the file.

    Note: The best way to save your script is by using a shortcut. If you are using a Mac, use command + S, and on Windows use Ctrl + S. We will be saving a new version of the script every time some changes are made to it, so it is a good idea to use a shortcut instead of saving through the Filemenu.

    We have added a few lines to our script. Before we check whether it works or what it actually does, let's go through line 7:

    public int myNumber = 9;

    In simple words, this line declares a new number type variable named myNumber and assigns a value of 9 to it. We don't want to worry about theory too much now and want to write more code, right? Agreed, but we do need to remember a few things first.


    To create a new variable, we first need to declare it by saying what type of variable it is, and as we explored before, a variable type represents the content. This means that the content for the myNumber variable is a number. The keyword for whole number variables in C# is int and for different types of content, we assign a different keyword. We also have to give our variable a name; myNumber is fine for now. You can use any name you want, as long as it does not contain spaces or special characters.


    We have created our variable, and now we are giving it a value. To assign a value, we use the equals sign followed by the value. In this case, it is 9. To close the line, use a semicolon; this is always necessary. The program reads our script one line of code at a time, and by using the semicolon we are telling the program that the line of code ends there.

    Click play!

    Quite an exciting moment! Go back from MonoDevelop to Unity and click the Play button. Unity should print out two lines on the Console tab, looking like this:


    Unity executed the code in the variableScript component on the GameObject just after you clicked Play. We can see two lines printed on the Console window. We wrote a piece of code asking Unity to print these two values the Console window. Let's look again at lines 11 and 13. Everything inside the brackets in the Debug.Log function will be printed to the Unity Console. It can be a number, text, or even an equation:


    So, line 11 is asking, "Hey Unity, print the result of 2 + 9 on the console!" Line 14 is using the myNumber variable's value directly and adding it to the number 11.

    Thus, the point of this exercise is to demonstrate that you can store and use whatever values you want using variables, and use their names directly to perform operations.

    How to change variables

    Since myNumber is a variable, the value that it stores can vary. If we change what is stored in it, the answer to the equation will also change. Follow these steps:

    1. Stop Unity by pressing the Stop button and change 9 to 19 in the Unity Inspector tab

    2. Notice that when you restart the game, the answer will be 30

    I bet you have noticed the public keyword at the very beginning of the line that declares the myNumber variable. Let me explain what it means. It's called an access modifier. We use these to specify the accessibility of a variable. The public keyword means that the variable can be seen by code outside our script. Look again at the Unity Inspector tab. You can see the value of myNumber there because it is public. The private keyword, however, means that the variable can be accessed only by code in the same class.

    Note: Private variables are not visible in the Unity Inspector tab. If you wish to control or view them, make them public.

    Watch for a possible gotcha when using public variables

    Unity gives us great flexibility with editing or reading public variables in the Inspector tab. You will be using public variables most of the time. Now, I want to make you aware of something that might give you a headache sometimes.

    Note: All public variable values are overridden by the Unity Inspector tab.

    Let's look back at line 6; we had assigned our variable a value of 9. This value will be copied to the Unity Inspector. From now on, the value from Inspector is taken into account and not the value in the script, even if you change it. Therefore, be careful as this is very easy to forget.

    In the Inspector panel, try changing the value of myNumber to some other value, even a negative value. Notice the change in the answer in the Console tab.


    This tutorial is an excerpt from "Learning C# 7 By Developing Games with Unity 2017 - Third Edition" by Micael DaGraca, Greg Lukosek and published by Packt.

    Get the complete eBook for just $10 (limited period offer).

    Thanks for reading! Learn more on the Packt Hub: Creating interactive Unity character animations and avatars [Tutorial]

      Report Article

    User Feedback

    There are no comments to display.

    Create an account or sign in to comment

    You need to be a member in order to leave a comment

    Create an account

    Sign up for a new account in our community. It's easy!

    Register a new account

    Sign in

    Already have an account? Sign in here.

    Sign In Now

  • Advertisement
  • Advertisement
  • Latest Featured Articles

  • Featured Blogs

  • Advertisement
  • Popular Now

  • Similar Content

    • By squirrelboy1225
      Hi! We recently released an alpha demo for our typing dungeon crawling game, Backspace Bouken. You can find it on itch.io, and we also have a Steam page where you can wishlist the full game. We also have a proper Gamedev.net project here: 
      We've been working on this game for about 10 months and will be releasing it in 2019. You can find our mailing list/social media info on our website if you want to follow along with development!
    • By horror_man
      Hello, I'm currently searching for additional talented and passionate members for our team that's creating a small horror game.
      About the game: The game would be a small sci-fi/post-apocalyptic survival horror 3D game with FPS (First person shooter) mechanics and an original setting and story based in a book (which I'm writing) scene, where a group of prisoners are left behind in an abandoned underground facility. It would play similar to Dead Space combined with Penumbra and SCP: Secret Laboratory, with the option of playing solo or multiplayer.
      Engine that'd be used to create the game: Unity
      About me: I'm a music composer with more than 4 years of experience and I'm fairly new in this game development world, and I'm currently leading the team that'd be creating this beautiful and horrifying game. I decided that making the book which I'm writing into a game would be really cool, and I got more motivated about doing so some time ago when I got a bunch of expensive Unity assets for a very low price. However, I researched about how to do things right in game development so I reduced the scope of it as much as I could so that's why this game is really based in a scene of the book and not the entire thing. Also I'm currently learning how to use Unity and learning how to program in C#.
      Our team right now consists of: Me (Game Designer, Creator, Music Composer, Writer), 2 3D Modelers, 5 Game Programmers, 1 Sound Effect Designer, 1 3D Animator and 2 2D Artists.
      Who am I looking for: We are looking for a talented and passionated 3D Environment Artist that's experienced in the modeling of closed environments and is familiar with the horror and sci-fi genre.
      Right now the game is in mid development and you can see more information about it and follow our progress in our game jolt page here: https://gamejolt.com/games/devilspunishment/391190 . We expect to finish some sort of prototype in 3 months from now.
      This is a contract rev-share position
      If you are interested in joining, contributing or have questions about the project then let's talk. You can message me in Discord: world_creator#9524
    • By INTwindwolf

      INT is a 3D Sci-fi RPG with a strong emphasis on story, role playing, and innovative RPG features such as randomized companions. The focus is on the journey through a war-torn world with fast-paced combat against hordes of enemies. The player must accomplish quests like a traditional RPG, complete objectives, and meet lively crew members who will aid in the player's survival. Throughout the game you can side and complete missions through criminal cartels, and the two major combatants, the UCE and ACP, of the Interstellar Civil War.
      Please note that all of our current positions are remote work. You will not be required to travel.
      For more information about us, follow the links listed below.
      INT Official website
      IndieDB page
      Also follow social media platforms for the latest news regarding our projects.
      Website Manager
      3D Character Modeller
      3D Environment Modeller
      3D Animator
      Unity Engine Programmer
      The project is marching increasingly closer to be ready for our crowd-funding campaign. Being an Indie team we do not have the creative restrictions often imposed by publishers or other third parties. We are extremely conscientious of our work and continuously uphold a high level of quality throughout our project.
      We are unable to offer wages or per-item payments at this time. However revenue-sharing from crowd-funding is offered to team members who contribute 15-20 hours per week to company projects, as well as maintain constant communication and adhere to deadlines. Your understanding is dearly appreciated.
      TO APPLY
      Please send your Cover Letter, CV, Portfolio (if applicable), and other relevant documents/information to this email: JohnHR@int-game.net
      Thank you for your time! Please feel free to contact me via the email provided should you have any questions or are interested to apply for this position. We look forward to hearing from you!
      John Shen
      HR Lead
      Starboard Games LLC
    • By DreamcityClass
      Dream City: Classified – "Survival Code" (Proof of Concept Framework)
      Episodic, 3D 3rd Person Co-op, Action Adventure Puzzle Plat-former
      Hey everyone I'm looking for a PART TIME/ HOBBYIST PROGRAMMER with an interest in the "Afropunk" style and culture. He would need a understanding of Unity python and marching cubes, or a willingness to learn it. I'm a character artist/ animator dabbling in coding and while starting to develop this game myself I just realized I don't have the time. I need help. I need a team. Hopefully some what passionate, but any little bit will help. You covering the coding would free me up to do more art, animation and character design, (and find more guys).
      The game is a procedural puzzle game, which aims to make all of the 5 (or more) characters on screen use different methods of traversal and fighting styles. The more characters in the party the more complicated the puzzles get. The players need to work together to survive (Dark Souls combat difficulty). There are charts, diagrams, and examples of each with assets I've already created, and a frame work you just need to stitch together. 
      But don't fear, this is a "BY THE EPISODE PROJECT", each of which will be individually Kickstarter'd. Once you sign on we will begin to understand one another's work habits, schedules, etc. while we make this FRAMEWORK. The framework is what we CROWD FUND for support to make the first episode.  
      If there is anyone out there interested in...
      Bringing more diversity to Indie games Working with an unique horror adventure world (World Anvil WIP) Working with an committed artist (who understands coding) and a remote growing team Developing a tight development plan, with passive income contracts: Patreon, product sales, (micros) and of course Revenue sharing Interested in working on a co-op TRINE ~like game mixed with DARK SOULS Willing to grow with this me/(us) as this company takes off.  
      Lets make a dream worth dreaming. 
      (Contact with questions)

    • By RoKabium Games
      Metis enemies – "Creeble" is the only creature on Metis that can crawl on the walls and it spins sticky webs that the Alien can get stuck in.

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!